blob: 3dc53eb873740cead952ce4ecd690bf63fd2916b [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoec925312012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000037#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkoaab83832012-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 Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
75 ArrayRef<RawComment> RawComments = Comments.getComments();
76
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.
88 ArrayRef<RawComment>::iterator Comment
89 = std::lower_bound(RawComments.begin(),
90 RawComments.end(),
Dmitri Gribenkofecc2e02012-06-21 21:02:45 +000091 RawComment(SourceMgr, SourceRange(DeclLoc)),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000092 BeforeThanCompare<RawComment>(SourceMgr));
93
94 // Decompose the location for the declaration and find the beginning of the
95 // file buffer.
96 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
97
98 // First check whether we have a trailing comment.
99 if (Comment != RawComments.end() &&
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000100 Comment->isDocumentation() && Comment->isTrailingComment() &&
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000101 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
102 std::pair<FileID, unsigned> CommentBeginDecomp
103 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
104 // Check that Doxygen trailing comment comes after the declaration, starts
105 // on the same line and in the same file as the declaration.
106 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
107 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
108 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
109 CommentBeginDecomp.second)) {
110 return &*Comment;
111 }
112 }
113
114 // The comment just after the declaration was not a trailing comment.
115 // Let's look at the previous comment.
116 if (Comment == RawComments.begin())
117 return NULL;
118 --Comment;
119
120 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000121 if (!Comment->isDocumentation() || Comment->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000122 return NULL;
123
124 // Decompose the end of the comment.
125 std::pair<FileID, unsigned> CommentEndDecomp
126 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
127
128 // If the comment and the declaration aren't in the same file, then they
129 // aren't related.
130 if (DeclLocDecomp.first != CommentEndDecomp.first)
131 return NULL;
132
133 // Get the corresponding buffer.
134 bool Invalid = false;
135 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
136 &Invalid).data();
137 if (Invalid)
138 return NULL;
139
140 // Extract text between the comment and declaration.
141 StringRef Text(Buffer + CommentEndDecomp.second,
142 DeclLocDecomp.second - CommentEndDecomp.second);
143
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000144 // There should be no other declarations or preprocessor directives between
145 // comment and declaration.
146 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 return NULL;
148
149 return &*Comment;
150}
151
152const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
153 // Check whether we have cached a comment string for this declaration
154 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000155 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000156 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000157 if (Pos != DeclComments.end()) {
158 RawAndParsedComment C = Pos->second;
159 return C.first;
160 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000161
162 const RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000163 // If we found a comment, it should be a documentation comment.
164 assert(!RC || RC->isDocumentation());
NAKAMURA Takumi38881722012-07-06 11:51:12 +0000165 DeclComments[D] = RawAndParsedComment(RC, (comments::FullComment *)NULL);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 return RC;
167}
168
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000169comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
170 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
171 = DeclComments.find(D);
172 const RawComment *RC;
173 if (Pos != DeclComments.end()) {
174 RawAndParsedComment C = Pos->second;
175 if (comments::FullComment *FC = C.second)
176 return FC;
177 RC = C.first;
178 } else
179 RC = getRawCommentForDecl(D);
180
181 if (!RC)
182 return NULL;
183
184 const StringRef RawText = RC->getRawText(SourceMgr);
185 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
186 RawText.begin(), RawText.end());
187
188 comments::Sema S(this->BumpAlloc);
189 comments::Parser P(L, S, this->BumpAlloc);
190
191 comments::FullComment *FC = P.parseFullComment();
192 DeclComments[D].second = FC;
193 return FC;
194}
195
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000196void
197ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
198 TemplateTemplateParmDecl *Parm) {
199 ID.AddInteger(Parm->getDepth());
200 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000201 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000202
203 TemplateParameterList *Params = Parm->getTemplateParameters();
204 ID.AddInteger(Params->size());
205 for (TemplateParameterList::const_iterator P = Params->begin(),
206 PEnd = Params->end();
207 P != PEnd; ++P) {
208 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
209 ID.AddInteger(0);
210 ID.AddBoolean(TTP->isParameterPack());
211 continue;
212 }
213
214 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
215 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000216 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000217 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000218 if (NTTP->isExpandedParameterPack()) {
219 ID.AddBoolean(true);
220 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000221 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
222 QualType T = NTTP->getExpansionType(I);
223 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
224 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000225 } else
226 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000227 continue;
228 }
229
230 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
231 ID.AddInteger(2);
232 Profile(ID, TTP);
233 }
234}
235
236TemplateTemplateParmDecl *
237ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000238 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000239 // Check if we already have a canonical template template parameter.
240 llvm::FoldingSetNodeID ID;
241 CanonicalTemplateTemplateParm::Profile(ID, TTP);
242 void *InsertPos = 0;
243 CanonicalTemplateTemplateParm *Canonical
244 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
245 if (Canonical)
246 return Canonical->getParam();
247
248 // Build a canonical template parameter list.
249 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000250 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000251 CanonParams.reserve(Params->size());
252 for (TemplateParameterList::const_iterator P = Params->begin(),
253 PEnd = Params->end();
254 P != PEnd; ++P) {
255 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
256 CanonParams.push_back(
257 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000258 SourceLocation(),
259 SourceLocation(),
260 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000261 TTP->getIndex(), 0, false,
262 TTP->isParameterPack()));
263 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000264 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
265 QualType T = getCanonicalType(NTTP->getType());
266 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
267 NonTypeTemplateParmDecl *Param;
268 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000269 SmallVector<QualType, 2> ExpandedTypes;
270 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000271 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
272 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
273 ExpandedTInfos.push_back(
274 getTrivialTypeSourceInfo(ExpandedTypes.back()));
275 }
276
277 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000278 SourceLocation(),
279 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000280 NTTP->getDepth(),
281 NTTP->getPosition(), 0,
282 T,
283 TInfo,
284 ExpandedTypes.data(),
285 ExpandedTypes.size(),
286 ExpandedTInfos.data());
287 } else {
288 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000289 SourceLocation(),
290 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000291 NTTP->getDepth(),
292 NTTP->getPosition(), 0,
293 T,
294 NTTP->isParameterPack(),
295 TInfo);
296 }
297 CanonParams.push_back(Param);
298
299 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000300 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
301 cast<TemplateTemplateParmDecl>(*P)));
302 }
303
304 TemplateTemplateParmDecl *CanonTTP
305 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
306 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000307 TTP->getPosition(),
308 TTP->isParameterPack(),
309 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000310 TemplateParameterList::Create(*this, SourceLocation(),
311 SourceLocation(),
312 CanonParams.data(),
313 CanonParams.size(),
314 SourceLocation()));
315
316 // Get the new insert position for the node we care about.
317 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
318 assert(Canonical == 0 && "Shouldn't be in the map!");
319 (void)Canonical;
320
321 // Create the canonical template template parameter entry.
322 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
323 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
324 return CanonTTP;
325}
326
Charles Davis53c59df2010-08-16 03:33:14 +0000327CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000328 if (!LangOpts.CPlusPlus) return 0;
329
Charles Davis6bcb07a2010-08-19 02:18:14 +0000330 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000331 case CXXABI_ARM:
332 return CreateARMCXXABI(*this);
333 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000334 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000335 case CXXABI_Microsoft:
336 return CreateMicrosoftCXXABI(*this);
337 }
David Blaikie8a40f702012-01-17 06:56:22 +0000338 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000339}
340
Douglas Gregore8bbc122011-09-02 00:18:52 +0000341static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000342 const LangOptions &LOpts) {
343 if (LOpts.FakeAddressSpaceMap) {
344 // The fake address space map must have a distinct entry for each
345 // language-specific address space.
346 static const unsigned FakeAddrSpaceMap[] = {
347 1, // opencl_global
348 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000349 3, // opencl_constant
350 4, // cuda_device
351 5, // cuda_constant
352 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000353 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000354 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000355 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000356 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000357 }
358}
359
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000360ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000361 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000362 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000363 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000364 unsigned size_reserve,
365 bool DelayInitialization)
366 : FunctionProtoTypes(this_()),
367 TemplateSpecializationTypes(this_()),
368 DependentTemplateSpecializationTypes(this_()),
369 SubstTemplateTemplateParmPacks(this_()),
370 GlobalNestedNameSpecifier(0),
371 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000372 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000373 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000374 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000375 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000376 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
377 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
378 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000379 NullTypeSourceInfo(QualType()),
380 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000381 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000382 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000383 Idents(idents), Selectors(sels),
384 BuiltinInfo(builtins),
385 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000386 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000387 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000388 LastSDM(0, 0),
389 UniqueBlockByRefTypeID(0)
390{
Mike Stump11289f42009-09-09 15:08:12 +0000391 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000392 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000393
394 if (!DelayInitialization) {
395 assert(t && "No target supplied for ASTContext initialization");
396 InitBuiltinTypes(*t);
397 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000398}
399
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000400ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000401 // Release the DenseMaps associated with DeclContext objects.
402 // FIXME: Is this the ideal solution?
403 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000404
Douglas Gregor5b11d492010-07-25 17:53:33 +0000405 // Call all of the deallocation functions.
406 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
407 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000408
Ted Kremenek076baeb2010-06-08 23:00:58 +0000409 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000410 // because they can contain DenseMaps.
411 for (llvm::DenseMap<const ObjCContainerDecl*,
412 const ASTRecordLayout*>::iterator
413 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
414 // Increment in loop to prevent using deallocated memory.
415 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
416 R->Destroy(*this);
417
Ted Kremenek076baeb2010-06-08 23:00:58 +0000418 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
419 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
420 // Increment in loop to prevent using deallocated memory.
421 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
422 R->Destroy(*this);
423 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000424
425 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
426 AEnd = DeclAttrs.end();
427 A != AEnd; ++A)
428 A->second->~AttrVec();
429}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000430
Douglas Gregor1a809332010-05-23 18:26:36 +0000431void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
432 Deallocations.push_back(std::make_pair(Callback, Data));
433}
434
Mike Stump11289f42009-09-09 15:08:12 +0000435void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000436ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000437 ExternalSource.reset(Source.take());
438}
439
Chris Lattner4eb445d2007-01-26 01:27:23 +0000440void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000441 llvm::errs() << "\n*** AST Context Stats:\n";
442 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000443
Douglas Gregora30d0462009-05-26 14:40:08 +0000444 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000445#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000446#define ABSTRACT_TYPE(Name, Parent)
447#include "clang/AST/TypeNodes.def"
448 0 // Extra
449 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000450
Chris Lattner4eb445d2007-01-26 01:27:23 +0000451 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
452 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000453 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000454 }
455
Douglas Gregora30d0462009-05-26 14:40:08 +0000456 unsigned Idx = 0;
457 unsigned TotalBytes = 0;
458#define TYPE(Name, Parent) \
459 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000460 llvm::errs() << " " << counts[Idx] << " " << #Name \
461 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000462 TotalBytes += counts[Idx] * sizeof(Name##Type); \
463 ++Idx;
464#define ABSTRACT_TYPE(Name, Parent)
465#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000466
Chandler Carruth3c147a72011-07-04 05:32:14 +0000467 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
468
Douglas Gregor7454c562010-07-02 20:37:36 +0000469 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000470 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
471 << NumImplicitDefaultConstructors
472 << " implicit default constructors created\n";
473 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
474 << NumImplicitCopyConstructors
475 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000476 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000477 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
478 << NumImplicitMoveConstructors
479 << " implicit move constructors created\n";
480 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
481 << NumImplicitCopyAssignmentOperators
482 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000483 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000484 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
485 << NumImplicitMoveAssignmentOperators
486 << " implicit move assignment operators created\n";
487 llvm::errs() << NumImplicitDestructorsDeclared << "/"
488 << NumImplicitDestructors
489 << " implicit destructors created\n";
490
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000491 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000492 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000493 ExternalSource->PrintStats();
494 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000495
Douglas Gregor5b11d492010-07-25 17:53:33 +0000496 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000497}
498
Douglas Gregor801c99d2011-08-12 06:49:56 +0000499TypedefDecl *ASTContext::getInt128Decl() const {
500 if (!Int128Decl) {
501 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
502 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
503 getTranslationUnitDecl(),
504 SourceLocation(),
505 SourceLocation(),
506 &Idents.get("__int128_t"),
507 TInfo);
508 }
509
510 return Int128Decl;
511}
512
513TypedefDecl *ASTContext::getUInt128Decl() const {
514 if (!UInt128Decl) {
515 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
516 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
517 getTranslationUnitDecl(),
518 SourceLocation(),
519 SourceLocation(),
520 &Idents.get("__uint128_t"),
521 TInfo);
522 }
523
524 return UInt128Decl;
525}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000526
John McCall48f2d582009-10-23 23:03:21 +0000527void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000528 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000529 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000530 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000531}
532
Douglas Gregore8bbc122011-09-02 00:18:52 +0000533void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
534 assert((!this->Target || this->Target == &Target) &&
535 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000536 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregore8bbc122011-09-02 00:18:52 +0000538 this->Target = &Target;
539
540 ABI.reset(createCXXABI(Target));
541 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
542
Chris Lattner970e54e2006-11-12 00:37:36 +0000543 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000544 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattner970e54e2006-11-12 00:37:36 +0000546 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000547 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000548 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000549 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000550 InitBuiltinType(CharTy, BuiltinType::Char_S);
551 else
552 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000553 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000554 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
555 InitBuiltinType(ShortTy, BuiltinType::Short);
556 InitBuiltinType(IntTy, BuiltinType::Int);
557 InitBuiltinType(LongTy, BuiltinType::Long);
558 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattner970e54e2006-11-12 00:37:36 +0000560 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000561 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
562 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
563 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
564 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
565 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000566
Chris Lattner970e54e2006-11-12 00:37:36 +0000567 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000568 InitBuiltinType(FloatTy, BuiltinType::Float);
569 InitBuiltinType(DoubleTy, BuiltinType::Double);
570 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000571
Chris Lattnerf122cef2009-04-30 02:43:43 +0000572 // GNU extension, 128-bit integers.
573 InitBuiltinType(Int128Ty, BuiltinType::Int128);
574 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
575
Chris Lattnerad3467e2010-12-25 23:25:43 +0000576 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000577 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000578 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
579 else // -fshort-wchar makes wchar_t be unsigned.
580 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
581 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000582 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000583
James Molloy36365542012-05-04 10:55:22 +0000584 WIntTy = getFromTargetType(Target.getWIntType());
585
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000586 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
587 InitBuiltinType(Char16Ty, BuiltinType::Char16);
588 else // C99
589 Char16Ty = getFromTargetType(Target.getChar16Type());
590
591 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
592 InitBuiltinType(Char32Ty, BuiltinType::Char32);
593 else // C99
594 Char32Ty = getFromTargetType(Target.getChar32Type());
595
Douglas Gregor4619e432008-12-05 23:32:09 +0000596 // Placeholder type for type-dependent expressions whose type is
597 // completely unknown. No code should ever check a type against
598 // DependentTy and users should never see it; however, it is here to
599 // help diagnose failures to properly check for type-dependent
600 // expressions.
601 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602
John McCall36e7fe32010-10-12 00:20:44 +0000603 // Placeholder type for functions.
604 InitBuiltinType(OverloadTy, BuiltinType::Overload);
605
John McCall0009fcc2011-04-26 20:42:42 +0000606 // Placeholder type for bound members.
607 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
608
John McCall526ab472011-10-25 17:37:35 +0000609 // Placeholder type for pseudo-objects.
610 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
611
John McCall31996342011-04-07 08:22:57 +0000612 // "any" type; useful for debugger-like clients.
613 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
614
John McCall8a6b59a2011-10-17 18:09:15 +0000615 // Placeholder type for unbridged ARC casts.
616 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
617
Chris Lattner970e54e2006-11-12 00:37:36 +0000618 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000619 FloatComplexTy = getComplexType(FloatTy);
620 DoubleComplexTy = getComplexType(DoubleTy);
621 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000622
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000623 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000624 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
625 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000626 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000627
628 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000629 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
630 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000631
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000632 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000633
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000634 // void * type
635 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000636
637 // nullptr type (C++0x 2.14.7)
638 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000639
640 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
641 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000642
643 // Builtin type used to help define __builtin_va_list.
644 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000645}
646
David Blaikie9c902b52011-09-25 23:23:43 +0000647DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000648 return SourceMgr.getDiagnostics();
649}
650
Douglas Gregor561eceb2010-08-30 16:49:28 +0000651AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
652 AttrVec *&Result = DeclAttrs[D];
653 if (!Result) {
654 void *Mem = Allocate(sizeof(AttrVec));
655 Result = new (Mem) AttrVec;
656 }
657
658 return *Result;
659}
660
661/// \brief Erase the attributes corresponding to the given declaration.
662void ASTContext::eraseDeclAttrs(const Decl *D) {
663 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
664 if (Pos != DeclAttrs.end()) {
665 Pos->second->~AttrVec();
666 DeclAttrs.erase(Pos);
667 }
668}
669
Douglas Gregor86d142a2009-10-08 07:24:58 +0000670MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000671ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000672 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000673 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000674 = InstantiatedFromStaticDataMember.find(Var);
675 if (Pos == InstantiatedFromStaticDataMember.end())
676 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000678 return Pos->second;
679}
680
Mike Stump11289f42009-09-09 15:08:12 +0000681void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000682ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000683 TemplateSpecializationKind TSK,
684 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000685 assert(Inst->isStaticDataMember() && "Not a static data member");
686 assert(Tmpl->isStaticDataMember() && "Not a static data member");
687 assert(!InstantiatedFromStaticDataMember[Inst] &&
688 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000689 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000690 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000691}
692
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000693FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
694 const FunctionDecl *FD){
695 assert(FD && "Specialization is 0");
696 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000697 = ClassScopeSpecializationPattern.find(FD);
698 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000699 return 0;
700
701 return Pos->second;
702}
703
704void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
705 FunctionDecl *Pattern) {
706 assert(FD && "Specialization is 0");
707 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000708 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000709}
710
John McCalle61f2ba2009-11-18 02:36:19 +0000711NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000712ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000713 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000714 = InstantiatedFromUsingDecl.find(UUD);
715 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000716 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000718 return Pos->second;
719}
720
721void
John McCallb96ec562009-12-04 22:46:56 +0000722ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
723 assert((isa<UsingDecl>(Pattern) ||
724 isa<UnresolvedUsingValueDecl>(Pattern) ||
725 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
726 "pattern decl is not a using decl");
727 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
728 InstantiatedFromUsingDecl[Inst] = Pattern;
729}
730
731UsingShadowDecl *
732ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
733 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
734 = InstantiatedFromUsingShadowDecl.find(Inst);
735 if (Pos == InstantiatedFromUsingShadowDecl.end())
736 return 0;
737
738 return Pos->second;
739}
740
741void
742ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
743 UsingShadowDecl *Pattern) {
744 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
745 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000746}
747
Anders Carlsson5da84842009-09-01 04:26:58 +0000748FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
749 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
750 = InstantiatedFromUnnamedFieldDecl.find(Field);
751 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
752 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Anders Carlsson5da84842009-09-01 04:26:58 +0000754 return Pos->second;
755}
756
757void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
758 FieldDecl *Tmpl) {
759 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
760 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
761 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
762 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000763
Anders Carlsson5da84842009-09-01 04:26:58 +0000764 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
765}
766
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000767bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
768 const FieldDecl *LastFD) const {
769 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000770 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000771}
772
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000773bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
774 const FieldDecl *LastFD) const {
775 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000776 FD->getBitWidthValue(*this) == 0 &&
777 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000778}
779
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000780bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
781 const FieldDecl *LastFD) const {
782 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000783 FD->getBitWidthValue(*this) &&
784 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000785}
786
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000787bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000788 const FieldDecl *LastFD) const {
789 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000790 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000791}
792
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000793bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000794 const FieldDecl *LastFD) const {
795 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000796 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000797}
798
Douglas Gregor832940b2010-03-02 23:58:15 +0000799ASTContext::overridden_cxx_method_iterator
800ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
801 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
802 = OverriddenMethods.find(Method);
803 if (Pos == OverriddenMethods.end())
804 return 0;
805
806 return Pos->second.begin();
807}
808
809ASTContext::overridden_cxx_method_iterator
810ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
811 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
812 = OverriddenMethods.find(Method);
813 if (Pos == OverriddenMethods.end())
814 return 0;
815
816 return Pos->second.end();
817}
818
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000819unsigned
820ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
821 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
822 = OverriddenMethods.find(Method);
823 if (Pos == OverriddenMethods.end())
824 return 0;
825
826 return Pos->second.size();
827}
828
Douglas Gregor832940b2010-03-02 23:58:15 +0000829void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
830 const CXXMethodDecl *Overridden) {
831 OverriddenMethods[Method].push_back(Overridden);
832}
833
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000834void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
835 assert(!Import->NextLocalImport && "Import declaration already in the chain");
836 assert(!Import->isFromASTFile() && "Non-local import declaration");
837 if (!FirstLocalImport) {
838 FirstLocalImport = Import;
839 LastLocalImport = Import;
840 return;
841 }
842
843 LastLocalImport->NextLocalImport = Import;
844 LastLocalImport = Import;
845}
846
Chris Lattner53cfe802007-07-18 17:52:12 +0000847//===----------------------------------------------------------------------===//
848// Type Sizing and Analysis
849//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000850
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000851/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
852/// scalar floating point type.
853const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000854 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000855 assert(BT && "Not a floating point type!");
856 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000857 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000858 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000859 case BuiltinType::Float: return Target->getFloatFormat();
860 case BuiltinType::Double: return Target->getDoubleFormat();
861 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000862 }
863}
864
Ken Dyck160146e2010-01-27 17:10:57 +0000865/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000866/// specified decl. Note that bitfields do not have a valid alignment, so
867/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000868/// If @p RefAsPointee, references are treated like their underlying type
869/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000870CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000871 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000872
John McCall94268702010-10-08 18:24:19 +0000873 bool UseAlignAttrOnly = false;
874 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
875 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000876
John McCall94268702010-10-08 18:24:19 +0000877 // __attribute__((aligned)) can increase or decrease alignment
878 // *except* on a struct or struct member, where it only increases
879 // alignment unless 'packed' is also specified.
880 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000881 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000882 // ignore that possibility; Sema should diagnose it.
883 if (isa<FieldDecl>(D)) {
884 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
885 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
886 } else {
887 UseAlignAttrOnly = true;
888 }
889 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000890 else if (isa<FieldDecl>(D))
891 UseAlignAttrOnly =
892 D->hasAttr<PackedAttr>() ||
893 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000894
John McCall4e819612011-01-20 07:57:12 +0000895 // If we're using the align attribute only, just ignore everything
896 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000897 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000898 // do nothing
899
John McCall94268702010-10-08 18:24:19 +0000900 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000901 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000902 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000903 if (RefAsPointee)
904 T = RT->getPointeeType();
905 else
906 T = getPointerType(RT->getPointeeType());
907 }
908 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000909 // Adjust alignments of declarations with array type by the
910 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000911 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000912 const ArrayType *arrayType;
913 if (MinWidth && (arrayType = getAsArrayType(T))) {
914 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000915 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000916 else if (isa<ConstantArrayType>(arrayType) &&
917 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000919
John McCall33ddac02011-01-19 10:06:00 +0000920 // Walk through any array types while we're at it.
921 T = getBaseElementType(arrayType);
922 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000923 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000924 }
John McCall4e819612011-01-20 07:57:12 +0000925
926 // Fields can be subject to extra alignment constraints, like if
927 // the field is packed, the struct is packed, or the struct has a
928 // a max-field-alignment constraint (#pragma pack). So calculate
929 // the actual alignment of the field within the struct, and then
930 // (as we're expected to) constrain that by the alignment of the type.
931 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
932 // So calculate the alignment of the field.
933 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
934
935 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000936 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000937
938 // Use the GCD of that and the offset within the record.
939 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
940 if (offset > 0) {
941 // Alignment is always a power of 2, so the GCD will be a power of 2,
942 // which means we get to do this crazy thing instead of Euclid's.
943 uint64_t lowBitOfOffset = offset & (~offset + 1);
944 if (lowBitOfOffset < fieldAlign)
945 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
946 }
947
948 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000949 }
Chris Lattner68061312009-01-24 21:53:27 +0000950 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000951
Ken Dyckcc56c542011-01-15 18:38:59 +0000952 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000953}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000954
John McCall87fe5d52010-05-20 01:18:31 +0000955std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000956ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000957 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000958 return std::make_pair(toCharUnitsFromBits(Info.first),
959 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000960}
961
962std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000963ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000964 return getTypeInfoInChars(T.getTypePtr());
965}
966
Daniel Dunbarc6475872012-03-09 04:12:54 +0000967std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
968 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
969 if (it != MemoizedTypeInfo.end())
970 return it->second;
971
972 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
973 MemoizedTypeInfo.insert(std::make_pair(T, Info));
974 return Info;
975}
976
977/// getTypeInfoImpl - Return the size of the specified type, in bits. This
978/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000979///
980/// FIXME: Pointers into different addr spaces could have different sizes and
981/// alignment requirements: getPointerInfo should take an AddrSpace, this
982/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000983std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000984ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000985 uint64_t Width=0;
986 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000987 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000988#define TYPE(Class, Base)
989#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000990#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000991#define DEPENDENT_TYPE(Class, Base) case Type::Class:
992#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000993 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000994
Chris Lattner355332d2007-07-13 22:27:08 +0000995 case Type::FunctionNoProto:
996 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000997 // GCC extension: alignof(function) = 32 bits
998 Width = 0;
999 Align = 32;
1000 break;
1001
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001002 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001003 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001004 Width = 0;
1005 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1006 break;
1007
Steve Naroff5c131802007-08-30 01:06:46 +00001008 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001009 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001010
Chris Lattner37e05872008-03-05 18:54:05 +00001011 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001012 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001013 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1014 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001015 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001016 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001017 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001018 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001019 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001020 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001021 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001022 const VectorType *VT = cast<VectorType>(T);
1023 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1024 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001025 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001026 // If the alignment is not a power of 2, round up to the next power of 2.
1027 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001028 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001029 Align = llvm::NextPowerOf2(Align);
1030 Width = llvm::RoundUpToAlignment(Width, Align);
1031 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001032 break;
1033 }
Chris Lattner647fb222007-07-18 18:26:58 +00001034
Chris Lattner7570e9c2008-03-08 08:52:55 +00001035 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001036 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001037 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001038 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001039 // GCC extension: alignof(void) = 8 bits.
1040 Width = 0;
1041 Align = 8;
1042 break;
1043
Chris Lattner6a4f7452007-12-19 19:23:28 +00001044 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001045 Width = Target->getBoolWidth();
1046 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001047 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001048 case BuiltinType::Char_S:
1049 case BuiltinType::Char_U:
1050 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001051 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001052 Width = Target->getCharWidth();
1053 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001054 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001055 case BuiltinType::WChar_S:
1056 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 Width = Target->getWCharWidth();
1058 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001059 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001060 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001061 Width = Target->getChar16Width();
1062 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001063 break;
1064 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001065 Width = Target->getChar32Width();
1066 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001067 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001068 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001069 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001070 Width = Target->getShortWidth();
1071 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001072 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001073 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001074 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001075 Width = Target->getIntWidth();
1076 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001077 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001078 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001079 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001080 Width = Target->getLongWidth();
1081 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001082 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001083 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001084 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001085 Width = Target->getLongLongWidth();
1086 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001087 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001088 case BuiltinType::Int128:
1089 case BuiltinType::UInt128:
1090 Width = 128;
1091 Align = 128; // int128_t is 128-bit aligned on all targets.
1092 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001093 case BuiltinType::Half:
1094 Width = Target->getHalfWidth();
1095 Align = Target->getHalfAlign();
1096 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001097 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 Width = Target->getFloatWidth();
1099 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001100 break;
1101 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001102 Width = Target->getDoubleWidth();
1103 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001104 break;
1105 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001106 Width = Target->getLongDoubleWidth();
1107 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001108 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001109 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001110 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1111 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001112 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001113 case BuiltinType::ObjCId:
1114 case BuiltinType::ObjCClass:
1115 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001116 Width = Target->getPointerWidth(0);
1117 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001118 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001119 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001120 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001121 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001122 Width = Target->getPointerWidth(0);
1123 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001124 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001125 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001126 unsigned AS = getTargetAddressSpace(
1127 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001128 Width = Target->getPointerWidth(AS);
1129 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001130 break;
1131 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001132 case Type::LValueReference:
1133 case Type::RValueReference: {
1134 // alignof and sizeof should never enter this code path here, so we go
1135 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001136 unsigned AS = getTargetAddressSpace(
1137 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 Width = Target->getPointerWidth(AS);
1139 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001140 break;
1141 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001142 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001143 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001144 Width = Target->getPointerWidth(AS);
1145 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001146 break;
1147 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001148 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001149 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001150 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001151 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001152 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001153 Align = PtrDiffInfo.second;
1154 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001155 }
Chris Lattner647fb222007-07-18 18:26:58 +00001156 case Type::Complex: {
1157 // Complex types have the same alignment as their elements, but twice the
1158 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001159 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001160 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001161 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001162 Align = EltInfo.second;
1163 break;
1164 }
John McCall8b07ec22010-05-15 11:32:37 +00001165 case Type::ObjCObject:
1166 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001167 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001168 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001169 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001170 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001171 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001172 break;
1173 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001174 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001175 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001176 const TagType *TT = cast<TagType>(T);
1177
1178 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001179 Width = 8;
1180 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001181 break;
1182 }
Mike Stump11289f42009-09-09 15:08:12 +00001183
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001184 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001185 return getTypeInfo(ET->getDecl()->getIntegerType());
1186
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001187 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001188 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001189 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001190 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001191 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001192 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001193
Chris Lattner63d2b362009-10-22 05:17:15 +00001194 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001195 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1196 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001197
Richard Smith30482bc2011-02-20 03:19:35 +00001198 case Type::Auto: {
1199 const AutoType *A = cast<AutoType>(T);
1200 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001201 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001202 }
1203
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001204 case Type::Paren:
1205 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1206
Douglas Gregoref462e62009-04-30 17:32:17 +00001207 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001208 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001209 std::pair<uint64_t, unsigned> Info
1210 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001211 // If the typedef has an aligned attribute on it, it overrides any computed
1212 // alignment we have. This violates the GCC documentation (which says that
1213 // attribute(aligned) can only round up) but matches its implementation.
1214 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1215 Align = AttrAlign;
1216 else
1217 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001218 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001219 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001220 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001221
1222 case Type::TypeOfExpr:
1223 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1224 .getTypePtr());
1225
1226 case Type::TypeOf:
1227 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1228
Anders Carlsson81df7b82009-06-24 19:06:50 +00001229 case Type::Decltype:
1230 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1231 .getTypePtr());
1232
Alexis Hunte852b102011-05-24 22:41:36 +00001233 case Type::UnaryTransform:
1234 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1235
Abramo Bagnara6150c882010-05-11 21:36:43 +00001236 case Type::Elaborated:
1237 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001238
John McCall81904512011-01-06 01:58:22 +00001239 case Type::Attributed:
1240 return getTypeInfo(
1241 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1242
Richard Smith3f1b5d02011-05-05 21:57:07 +00001243 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001244 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001245 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001246 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1247 // A type alias template specialization may refer to a typedef with the
1248 // aligned attribute on it.
1249 if (TST->isTypeAlias())
1250 return getTypeInfo(TST->getAliasedType().getTypePtr());
1251 else
1252 return getTypeInfo(getCanonicalType(T));
1253 }
1254
Eli Friedman0dfb8892011-10-06 23:00:33 +00001255 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001256 std::pair<uint64_t, unsigned> Info
1257 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1258 Width = Info.first;
1259 Align = Info.second;
1260 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1261 llvm::isPowerOf2_64(Width)) {
1262 // We can potentially perform lock-free atomic operations for this
1263 // type; promote the alignment appropriately.
1264 // FIXME: We could potentially promote the width here as well...
1265 // is that worthwhile? (Non-struct atomic types generally have
1266 // power-of-two size anyway, but structs might not. Requires a bit
1267 // of implementation work to make sure we zero out the extra bits.)
1268 Align = static_cast<unsigned>(Width);
1269 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001270 }
1271
Douglas Gregoref462e62009-04-30 17:32:17 +00001272 }
Mike Stump11289f42009-09-09 15:08:12 +00001273
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001274 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001275 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001276}
1277
Ken Dyckcc56c542011-01-15 18:38:59 +00001278/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1279CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1280 return CharUnits::fromQuantity(BitSize / getCharWidth());
1281}
1282
Ken Dyckb0fcc592011-02-11 01:54:29 +00001283/// toBits - Convert a size in characters to a size in characters.
1284int64_t ASTContext::toBits(CharUnits CharSize) const {
1285 return CharSize.getQuantity() * getCharWidth();
1286}
1287
Ken Dyck8c89d592009-12-22 14:23:30 +00001288/// getTypeSizeInChars - Return the size of the specified type, in characters.
1289/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001290CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001291 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001292}
Jay Foad39c79802011-01-12 09:06:06 +00001293CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001294 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001295}
1296
Ken Dycka6046ab2010-01-26 17:25:18 +00001297/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001298/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001299CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001300 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001301}
Jay Foad39c79802011-01-12 09:06:06 +00001302CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001303 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001304}
1305
Chris Lattnera3402cd2009-01-27 18:08:34 +00001306/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1307/// type for the current target in bits. This can be different than the ABI
1308/// alignment in cases where it is beneficial for performance to overalign
1309/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001310unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001311 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001312
1313 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001314 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001315 T = CT->getElementType().getTypePtr();
1316 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001317 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1318 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001319 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1320
Chris Lattnera3402cd2009-01-27 18:08:34 +00001321 return ABIAlign;
1322}
1323
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001324/// DeepCollectObjCIvars -
1325/// This routine first collects all declared, but not synthesized, ivars in
1326/// super class and then collects all ivars, including those synthesized for
1327/// current class. This routine is used for implementation of current class
1328/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001329///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001330void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1331 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001332 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001333 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1334 DeepCollectObjCIvars(SuperClass, false, Ivars);
1335 if (!leafClass) {
1336 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1337 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001338 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001339 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001340 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001341 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001342 Iv= Iv->getNextIvar())
1343 Ivars.push_back(Iv);
1344 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001345}
1346
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001347/// CollectInheritedProtocols - Collect all protocols in current class and
1348/// those inherited by it.
1349void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001350 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001351 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001352 // We can use protocol_iterator here instead of
1353 // all_referenced_protocol_iterator since we are walking all categories.
1354 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1355 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001356 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001357 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001358 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001359 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001360 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001361 CollectInheritedProtocols(*P, Protocols);
1362 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001363 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001364
1365 // Categories of this Interface.
1366 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1367 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1368 CollectInheritedProtocols(CDeclChain, Protocols);
1369 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1370 while (SD) {
1371 CollectInheritedProtocols(SD, Protocols);
1372 SD = SD->getSuperClass();
1373 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001374 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001375 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001376 PE = OC->protocol_end(); P != PE; ++P) {
1377 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001378 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001379 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1380 PE = Proto->protocol_end(); P != PE; ++P)
1381 CollectInheritedProtocols(*P, Protocols);
1382 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001383 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001384 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1385 PE = OP->protocol_end(); P != PE; ++P) {
1386 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001387 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001388 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1389 PE = Proto->protocol_end(); P != PE; ++P)
1390 CollectInheritedProtocols(*P, Protocols);
1391 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001392 }
1393}
1394
Jay Foad39c79802011-01-12 09:06:06 +00001395unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001396 unsigned count = 0;
1397 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001398 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1399 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001400 count += CDecl->ivar_size();
1401
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001402 // Count ivar defined in this class's implementation. This
1403 // includes synthesized ivars.
1404 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001405 count += ImplDecl->ivar_size();
1406
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001407 return count;
1408}
1409
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001410bool ASTContext::isSentinelNullExpr(const Expr *E) {
1411 if (!E)
1412 return false;
1413
1414 // nullptr_t is always treated as null.
1415 if (E->getType()->isNullPtrType()) return true;
1416
1417 if (E->getType()->isAnyPointerType() &&
1418 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1419 Expr::NPC_ValueDependentIsNull))
1420 return true;
1421
1422 // Unfortunately, __null has type 'int'.
1423 if (isa<GNUNullExpr>(E)) return true;
1424
1425 return false;
1426}
1427
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001428/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1429ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1430 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1431 I = ObjCImpls.find(D);
1432 if (I != ObjCImpls.end())
1433 return cast<ObjCImplementationDecl>(I->second);
1434 return 0;
1435}
1436/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1437ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1438 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1439 I = ObjCImpls.find(D);
1440 if (I != ObjCImpls.end())
1441 return cast<ObjCCategoryImplDecl>(I->second);
1442 return 0;
1443}
1444
1445/// \brief Set the implementation of ObjCInterfaceDecl.
1446void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1447 ObjCImplementationDecl *ImplD) {
1448 assert(IFaceD && ImplD && "Passed null params");
1449 ObjCImpls[IFaceD] = ImplD;
1450}
1451/// \brief Set the implementation of ObjCCategoryDecl.
1452void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1453 ObjCCategoryImplDecl *ImplD) {
1454 assert(CatD && ImplD && "Passed null params");
1455 ObjCImpls[CatD] = ImplD;
1456}
1457
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001458ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1459 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1460 return ID;
1461 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1462 return CD->getClassInterface();
1463 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1464 return IMD->getClassInterface();
1465
1466 return 0;
1467}
1468
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001469/// \brief Get the copy initialization expression of VarDecl,or NULL if
1470/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001471Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001472 assert(VD && "Passed null params");
1473 assert(VD->hasAttr<BlocksAttr>() &&
1474 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001475 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001476 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001477 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1478}
1479
1480/// \brief Set the copy inialization expression of a block var decl.
1481void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1482 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001483 assert(VD->hasAttr<BlocksAttr>() &&
1484 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001485 BlockVarCopyInits[VD] = Init;
1486}
1487
John McCallbcd03502009-12-07 02:54:59 +00001488TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001489 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001490 if (!DataSize)
1491 DataSize = TypeLoc::getFullDataSizeForType(T);
1492 else
1493 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001494 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001495
John McCallbcd03502009-12-07 02:54:59 +00001496 TypeSourceInfo *TInfo =
1497 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1498 new (TInfo) TypeSourceInfo(T);
1499 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001500}
1501
John McCallbcd03502009-12-07 02:54:59 +00001502TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001503 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001504 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001505 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001506 return DI;
1507}
1508
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001509const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001510ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001511 return getObjCLayout(D, 0);
1512}
1513
1514const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001515ASTContext::getASTObjCImplementationLayout(
1516 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001517 return getObjCLayout(D->getClassInterface(), D);
1518}
1519
Chris Lattner983a8bb2007-07-13 22:13:22 +00001520//===----------------------------------------------------------------------===//
1521// Type creation/memoization methods
1522//===----------------------------------------------------------------------===//
1523
Jay Foad39c79802011-01-12 09:06:06 +00001524QualType
John McCall33ddac02011-01-19 10:06:00 +00001525ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1526 unsigned fastQuals = quals.getFastQualifiers();
1527 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001528
1529 // Check if we've already instantiated this type.
1530 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001531 ExtQuals::Profile(ID, baseType, quals);
1532 void *insertPos = 0;
1533 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1534 assert(eq->getQualifiers() == quals);
1535 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001536 }
1537
John McCall33ddac02011-01-19 10:06:00 +00001538 // If the base type is not canonical, make the appropriate canonical type.
1539 QualType canon;
1540 if (!baseType->isCanonicalUnqualified()) {
1541 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001542 canonSplit.Quals.addConsistentQualifiers(quals);
1543 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001544
1545 // Re-find the insert position.
1546 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1547 }
1548
1549 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1550 ExtQualNodes.InsertNode(eq, insertPos);
1551 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001552}
1553
Jay Foad39c79802011-01-12 09:06:06 +00001554QualType
1555ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001556 QualType CanT = getCanonicalType(T);
1557 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001558 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001559
John McCall8ccfcb52009-09-24 19:53:00 +00001560 // If we are composing extended qualifiers together, merge together
1561 // into one ExtQuals node.
1562 QualifierCollector Quals;
1563 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001564
John McCall8ccfcb52009-09-24 19:53:00 +00001565 // If this type already has an address space specified, it cannot get
1566 // another one.
1567 assert(!Quals.hasAddressSpace() &&
1568 "Type cannot be in multiple addr spaces!");
1569 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001570
John McCall8ccfcb52009-09-24 19:53:00 +00001571 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001572}
1573
Chris Lattnerd60183d2009-02-18 22:53:11 +00001574QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001575 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001576 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001577 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001578 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001579
John McCall53fa7142010-12-24 02:08:15 +00001580 if (const PointerType *ptr = T->getAs<PointerType>()) {
1581 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001582 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001583 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1584 return getPointerType(ResultType);
1585 }
1586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCall8ccfcb52009-09-24 19:53:00 +00001588 // If we are composing extended qualifiers together, merge together
1589 // into one ExtQuals node.
1590 QualifierCollector Quals;
1591 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCall8ccfcb52009-09-24 19:53:00 +00001593 // If this type already has an ObjCGC specified, it cannot get
1594 // another one.
1595 assert(!Quals.hasObjCGCAttr() &&
1596 "Type cannot have multiple ObjCGCs!");
1597 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001598
John McCall8ccfcb52009-09-24 19:53:00 +00001599 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001600}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001601
John McCall4f5019e2010-12-19 02:44:49 +00001602const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1603 FunctionType::ExtInfo Info) {
1604 if (T->getExtInfo() == Info)
1605 return T;
1606
1607 QualType Result;
1608 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1609 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1610 } else {
1611 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1612 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1613 EPI.ExtInfo = Info;
1614 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1615 FPT->getNumArgs(), EPI);
1616 }
1617
1618 return cast<FunctionType>(Result.getTypePtr());
1619}
1620
Chris Lattnerc6395932007-06-22 20:56:16 +00001621/// getComplexType - Return the uniqued reference to the type for a complex
1622/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001623QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001624 // Unique pointers, to guarantee there is only one pointer of a particular
1625 // structure.
1626 llvm::FoldingSetNodeID ID;
1627 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattnerc6395932007-06-22 20:56:16 +00001629 void *InsertPos = 0;
1630 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1631 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001632
Chris Lattnerc6395932007-06-22 20:56:16 +00001633 // If the pointee type isn't canonical, this won't be a canonical type either,
1634 // so fill in the canonical type field.
1635 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001636 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001637 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattnerc6395932007-06-22 20:56:16 +00001639 // Get the new insert position for the node we care about.
1640 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001641 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001642 }
John McCall90d1c2d2009-09-24 23:30:46 +00001643 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001644 Types.push_back(New);
1645 ComplexTypes.InsertNode(New, InsertPos);
1646 return QualType(New, 0);
1647}
1648
Chris Lattner970e54e2006-11-12 00:37:36 +00001649/// getPointerType - Return the uniqued reference to the type for a pointer to
1650/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001651QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001652 // Unique pointers, to guarantee there is only one pointer of a particular
1653 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001654 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001655 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattner67521df2007-01-27 01:29:36 +00001657 void *InsertPos = 0;
1658 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001659 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001660
Chris Lattner7ccecb92006-11-12 08:50:50 +00001661 // If the pointee type isn't canonical, this won't be a canonical type either,
1662 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001663 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001664 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001665 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001666
Chris Lattner67521df2007-01-27 01:29:36 +00001667 // Get the new insert position for the node we care about.
1668 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001669 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001670 }
John McCall90d1c2d2009-09-24 23:30:46 +00001671 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001672 Types.push_back(New);
1673 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001674 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001675}
1676
Mike Stump11289f42009-09-09 15:08:12 +00001677/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001678/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001679QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001680 assert(T->isFunctionType() && "block of function types only");
1681 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001682 // structure.
1683 llvm::FoldingSetNodeID ID;
1684 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001685
Steve Naroffec33ed92008-08-27 16:04:49 +00001686 void *InsertPos = 0;
1687 if (BlockPointerType *PT =
1688 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1689 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001690
1691 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001692 // type either so fill in the canonical type field.
1693 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001694 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001695 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001696
Steve Naroffec33ed92008-08-27 16:04:49 +00001697 // Get the new insert position for the node we care about.
1698 BlockPointerType *NewIP =
1699 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001700 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001701 }
John McCall90d1c2d2009-09-24 23:30:46 +00001702 BlockPointerType *New
1703 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001704 Types.push_back(New);
1705 BlockPointerTypes.InsertNode(New, InsertPos);
1706 return QualType(New, 0);
1707}
1708
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001709/// getLValueReferenceType - Return the uniqued reference to the type for an
1710/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001711QualType
1712ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001713 assert(getCanonicalType(T) != OverloadTy &&
1714 "Unresolved overloaded function type");
1715
Bill Wendling3708c182007-05-27 10:15:43 +00001716 // Unique pointers, to guarantee there is only one pointer of a particular
1717 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001718 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001719 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001720
1721 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001722 if (LValueReferenceType *RT =
1723 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001724 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001725
John McCallfc93cf92009-10-22 22:37:11 +00001726 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1727
Bill Wendling3708c182007-05-27 10:15:43 +00001728 // If the referencee type isn't canonical, this won't be a canonical type
1729 // either, so fill in the canonical type field.
1730 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001731 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1732 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1733 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001734
Bill Wendling3708c182007-05-27 10:15:43 +00001735 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001736 LValueReferenceType *NewIP =
1737 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001738 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001739 }
1740
John McCall90d1c2d2009-09-24 23:30:46 +00001741 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001742 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1743 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001744 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001745 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001746
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001747 return QualType(New, 0);
1748}
1749
1750/// getRValueReferenceType - Return the uniqued reference to the type for an
1751/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001752QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001753 // Unique pointers, to guarantee there is only one pointer of a particular
1754 // structure.
1755 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001756 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001757
1758 void *InsertPos = 0;
1759 if (RValueReferenceType *RT =
1760 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1761 return QualType(RT, 0);
1762
John McCallfc93cf92009-10-22 22:37:11 +00001763 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1764
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001765 // If the referencee type isn't canonical, this won't be a canonical type
1766 // either, so fill in the canonical type field.
1767 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001768 if (InnerRef || !T.isCanonical()) {
1769 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1770 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001771
1772 // Get the new insert position for the node we care about.
1773 RValueReferenceType *NewIP =
1774 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001776 }
1777
John McCall90d1c2d2009-09-24 23:30:46 +00001778 RValueReferenceType *New
1779 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001780 Types.push_back(New);
1781 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001782 return QualType(New, 0);
1783}
1784
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001785/// getMemberPointerType - Return the uniqued reference to the type for a
1786/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001787QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001788 // Unique pointers, to guarantee there is only one pointer of a particular
1789 // structure.
1790 llvm::FoldingSetNodeID ID;
1791 MemberPointerType::Profile(ID, T, Cls);
1792
1793 void *InsertPos = 0;
1794 if (MemberPointerType *PT =
1795 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1796 return QualType(PT, 0);
1797
1798 // If the pointee or class type isn't canonical, this won't be a canonical
1799 // type either, so fill in the canonical type field.
1800 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001801 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001802 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1803
1804 // Get the new insert position for the node we care about.
1805 MemberPointerType *NewIP =
1806 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001807 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001808 }
John McCall90d1c2d2009-09-24 23:30:46 +00001809 MemberPointerType *New
1810 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001811 Types.push_back(New);
1812 MemberPointerTypes.InsertNode(New, InsertPos);
1813 return QualType(New, 0);
1814}
1815
Mike Stump11289f42009-09-09 15:08:12 +00001816/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001817/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001818QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001819 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001820 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001821 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001822 assert((EltTy->isDependentType() ||
1823 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001824 "Constant array of VLAs is illegal!");
1825
Chris Lattnere2df3f92009-05-13 04:12:56 +00001826 // Convert the array size into a canonical width matching the pointer size for
1827 // the target.
1828 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001829 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001830 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001831
Chris Lattner23b7eb62007-06-15 23:05:46 +00001832 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001833 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001834
Chris Lattner36f8e652007-01-27 08:31:04 +00001835 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001836 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001837 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001838 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001839
John McCall33ddac02011-01-19 10:06:00 +00001840 // If the element type isn't canonical or has qualifiers, this won't
1841 // be a canonical type either, so fill in the canonical type field.
1842 QualType Canon;
1843 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1844 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001845 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001846 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001847 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001848
Chris Lattner36f8e652007-01-27 08:31:04 +00001849 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001850 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001851 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001852 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
John McCall90d1c2d2009-09-24 23:30:46 +00001855 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001856 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001857 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001858 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001859 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001860}
1861
John McCall06549462011-01-18 08:40:38 +00001862/// getVariableArrayDecayedType - Turns the given type, which may be
1863/// variably-modified, into the corresponding type with all the known
1864/// sizes replaced with [*].
1865QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1866 // Vastly most common case.
1867 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001868
John McCall06549462011-01-18 08:40:38 +00001869 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001870
John McCall06549462011-01-18 08:40:38 +00001871 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001872 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001873 switch (ty->getTypeClass()) {
1874#define TYPE(Class, Base)
1875#define ABSTRACT_TYPE(Class, Base)
1876#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1877#include "clang/AST/TypeNodes.def"
1878 llvm_unreachable("didn't desugar past all non-canonical types?");
1879
1880 // These types should never be variably-modified.
1881 case Type::Builtin:
1882 case Type::Complex:
1883 case Type::Vector:
1884 case Type::ExtVector:
1885 case Type::DependentSizedExtVector:
1886 case Type::ObjCObject:
1887 case Type::ObjCInterface:
1888 case Type::ObjCObjectPointer:
1889 case Type::Record:
1890 case Type::Enum:
1891 case Type::UnresolvedUsing:
1892 case Type::TypeOfExpr:
1893 case Type::TypeOf:
1894 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001895 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001896 case Type::DependentName:
1897 case Type::InjectedClassName:
1898 case Type::TemplateSpecialization:
1899 case Type::DependentTemplateSpecialization:
1900 case Type::TemplateTypeParm:
1901 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001902 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001903 case Type::PackExpansion:
1904 llvm_unreachable("type should never be variably-modified");
1905
1906 // These types can be variably-modified but should never need to
1907 // further decay.
1908 case Type::FunctionNoProto:
1909 case Type::FunctionProto:
1910 case Type::BlockPointer:
1911 case Type::MemberPointer:
1912 return type;
1913
1914 // These types can be variably-modified. All these modifications
1915 // preserve structure except as noted by comments.
1916 // TODO: if we ever care about optimizing VLAs, there are no-op
1917 // optimizations available here.
1918 case Type::Pointer:
1919 result = getPointerType(getVariableArrayDecayedType(
1920 cast<PointerType>(ty)->getPointeeType()));
1921 break;
1922
1923 case Type::LValueReference: {
1924 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1925 result = getLValueReferenceType(
1926 getVariableArrayDecayedType(lv->getPointeeType()),
1927 lv->isSpelledAsLValue());
1928 break;
1929 }
1930
1931 case Type::RValueReference: {
1932 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1933 result = getRValueReferenceType(
1934 getVariableArrayDecayedType(lv->getPointeeType()));
1935 break;
1936 }
1937
Eli Friedman0dfb8892011-10-06 23:00:33 +00001938 case Type::Atomic: {
1939 const AtomicType *at = cast<AtomicType>(ty);
1940 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1941 break;
1942 }
1943
John McCall06549462011-01-18 08:40:38 +00001944 case Type::ConstantArray: {
1945 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1946 result = getConstantArrayType(
1947 getVariableArrayDecayedType(cat->getElementType()),
1948 cat->getSize(),
1949 cat->getSizeModifier(),
1950 cat->getIndexTypeCVRQualifiers());
1951 break;
1952 }
1953
1954 case Type::DependentSizedArray: {
1955 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1956 result = getDependentSizedArrayType(
1957 getVariableArrayDecayedType(dat->getElementType()),
1958 dat->getSizeExpr(),
1959 dat->getSizeModifier(),
1960 dat->getIndexTypeCVRQualifiers(),
1961 dat->getBracketsRange());
1962 break;
1963 }
1964
1965 // Turn incomplete types into [*] types.
1966 case Type::IncompleteArray: {
1967 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1968 result = getVariableArrayType(
1969 getVariableArrayDecayedType(iat->getElementType()),
1970 /*size*/ 0,
1971 ArrayType::Normal,
1972 iat->getIndexTypeCVRQualifiers(),
1973 SourceRange());
1974 break;
1975 }
1976
1977 // Turn VLA types into [*] types.
1978 case Type::VariableArray: {
1979 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1980 result = getVariableArrayType(
1981 getVariableArrayDecayedType(vat->getElementType()),
1982 /*size*/ 0,
1983 ArrayType::Star,
1984 vat->getIndexTypeCVRQualifiers(),
1985 vat->getBracketsRange());
1986 break;
1987 }
1988 }
1989
1990 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001991 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001992}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001993
Steve Naroffcadebd02007-08-30 18:14:25 +00001994/// getVariableArrayType - Returns a non-unique reference to the type for a
1995/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001996QualType ASTContext::getVariableArrayType(QualType EltTy,
1997 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001998 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001999 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002000 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002001 // Since we don't unique expressions, it isn't possible to unique VLA's
2002 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002003 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002004
John McCall33ddac02011-01-19 10:06:00 +00002005 // Be sure to pull qualifiers off the element type.
2006 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2007 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002008 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002009 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002010 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002011 }
2012
John McCall90d1c2d2009-09-24 23:30:46 +00002013 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002014 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002015
2016 VariableArrayTypes.push_back(New);
2017 Types.push_back(New);
2018 return QualType(New, 0);
2019}
2020
Douglas Gregor4619e432008-12-05 23:32:09 +00002021/// getDependentSizedArrayType - Returns a non-unique reference to
2022/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002023/// type.
John McCall33ddac02011-01-19 10:06:00 +00002024QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2025 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002026 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002027 unsigned elementTypeQuals,
2028 SourceRange brackets) const {
2029 assert((!numElements || numElements->isTypeDependent() ||
2030 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002031 "Size must be type- or value-dependent!");
2032
John McCall33ddac02011-01-19 10:06:00 +00002033 // Dependently-sized array types that do not have a specified number
2034 // of elements will have their sizes deduced from a dependent
2035 // initializer. We do no canonicalization here at all, which is okay
2036 // because they can't be used in most locations.
2037 if (!numElements) {
2038 DependentSizedArrayType *newType
2039 = new (*this, TypeAlignment)
2040 DependentSizedArrayType(*this, elementType, QualType(),
2041 numElements, ASM, elementTypeQuals,
2042 brackets);
2043 Types.push_back(newType);
2044 return QualType(newType, 0);
2045 }
2046
2047 // Otherwise, we actually build a new type every time, but we
2048 // also build a canonical type.
2049
2050 SplitQualType canonElementType = getCanonicalType(elementType).split();
2051
2052 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002053 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002054 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002055 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002056 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002057
John McCall33ddac02011-01-19 10:06:00 +00002058 // Look for an existing type with these properties.
2059 DependentSizedArrayType *canonTy =
2060 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002061
John McCall33ddac02011-01-19 10:06:00 +00002062 // If we don't have one, build one.
2063 if (!canonTy) {
2064 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002065 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002066 QualType(), numElements, ASM, elementTypeQuals,
2067 brackets);
2068 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2069 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002070 }
2071
John McCall33ddac02011-01-19 10:06:00 +00002072 // Apply qualifiers from the element type to the array.
2073 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002074 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002075
John McCall33ddac02011-01-19 10:06:00 +00002076 // If we didn't need extra canonicalization for the element type,
2077 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002078 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002079 return canon;
2080
2081 // Otherwise, we need to build a type which follows the spelling
2082 // of the element type.
2083 DependentSizedArrayType *sugaredType
2084 = new (*this, TypeAlignment)
2085 DependentSizedArrayType(*this, elementType, canon, numElements,
2086 ASM, elementTypeQuals, brackets);
2087 Types.push_back(sugaredType);
2088 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002089}
2090
John McCall33ddac02011-01-19 10:06:00 +00002091QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002092 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002093 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002094 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002095 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002096
John McCall33ddac02011-01-19 10:06:00 +00002097 void *insertPos = 0;
2098 if (IncompleteArrayType *iat =
2099 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2100 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002101
2102 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002103 // either, so fill in the canonical type field. We also have to pull
2104 // qualifiers off the element type.
2105 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002106
John McCall33ddac02011-01-19 10:06:00 +00002107 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2108 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002109 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002110 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002111 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002112
2113 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002114 IncompleteArrayType *existing =
2115 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2116 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002117 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002118
John McCall33ddac02011-01-19 10:06:00 +00002119 IncompleteArrayType *newType = new (*this, TypeAlignment)
2120 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002121
John McCall33ddac02011-01-19 10:06:00 +00002122 IncompleteArrayTypes.InsertNode(newType, insertPos);
2123 Types.push_back(newType);
2124 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002125}
2126
Steve Naroff91fcddb2007-07-18 18:00:27 +00002127/// getVectorType - Return the unique reference to a vector type of
2128/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002129QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002130 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002131 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002132
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002133 // Check if we've already instantiated a vector of this type.
2134 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002135 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002136
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002137 void *InsertPos = 0;
2138 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2139 return QualType(VTP, 0);
2140
2141 // If the element type isn't canonical, this won't be a canonical type either,
2142 // so fill in the canonical type field.
2143 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002144 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002145 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002147 // Get the new insert position for the node we care about.
2148 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002149 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002150 }
John McCall90d1c2d2009-09-24 23:30:46 +00002151 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002152 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002153 VectorTypes.InsertNode(New, InsertPos);
2154 Types.push_back(New);
2155 return QualType(New, 0);
2156}
2157
Nate Begemance4d7fc2008-04-18 23:10:10 +00002158/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002159/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002160QualType
2161ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002162 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002163
Steve Naroff91fcddb2007-07-18 18:00:27 +00002164 // Check if we've already instantiated a vector of this type.
2165 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002166 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002167 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002168 void *InsertPos = 0;
2169 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2170 return QualType(VTP, 0);
2171
2172 // If the element type isn't canonical, this won't be a canonical type either,
2173 // so fill in the canonical type field.
2174 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002175 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002176 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002177
Steve Naroff91fcddb2007-07-18 18:00:27 +00002178 // Get the new insert position for the node we care about.
2179 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002180 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002181 }
John McCall90d1c2d2009-09-24 23:30:46 +00002182 ExtVectorType *New = new (*this, TypeAlignment)
2183 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002184 VectorTypes.InsertNode(New, InsertPos);
2185 Types.push_back(New);
2186 return QualType(New, 0);
2187}
2188
Jay Foad39c79802011-01-12 09:06:06 +00002189QualType
2190ASTContext::getDependentSizedExtVectorType(QualType vecType,
2191 Expr *SizeExpr,
2192 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002193 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002194 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002195 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregor352169a2009-07-31 03:54:25 +00002197 void *InsertPos = 0;
2198 DependentSizedExtVectorType *Canon
2199 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2200 DependentSizedExtVectorType *New;
2201 if (Canon) {
2202 // We already have a canonical version of this array type; use it as
2203 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002204 New = new (*this, TypeAlignment)
2205 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2206 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002207 } else {
2208 QualType CanonVecTy = getCanonicalType(vecType);
2209 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002210 New = new (*this, TypeAlignment)
2211 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2212 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002213
2214 DependentSizedExtVectorType *CanonCheck
2215 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2217 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002218 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2219 } else {
2220 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2221 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002222 New = new (*this, TypeAlignment)
2223 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002224 }
2225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregor758a8692009-06-17 21:51:59 +00002227 Types.push_back(New);
2228 return QualType(New, 0);
2229}
2230
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002231/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002232///
Jay Foad39c79802011-01-12 09:06:06 +00002233QualType
2234ASTContext::getFunctionNoProtoType(QualType ResultTy,
2235 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002236 const CallingConv DefaultCC = Info.getCC();
2237 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2238 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002239 // Unique functions, to guarantee there is only one function of a particular
2240 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002241 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002242 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002243
Chris Lattner47955de2007-01-27 08:37:20 +00002244 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002245 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002246 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002247 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002248
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002249 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002250 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002251 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002252 Canonical =
2253 getFunctionNoProtoType(getCanonicalType(ResultTy),
2254 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattner47955de2007-01-27 08:37:20 +00002256 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002257 FunctionNoProtoType *NewIP =
2258 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002259 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002260 }
Mike Stump11289f42009-09-09 15:08:12 +00002261
Roman Divacky65b88cd2011-03-01 17:40:53 +00002262 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002263 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002264 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002265 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002266 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002267 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002268}
2269
2270/// getFunctionType - Return a normal function type with a typed argument
2271/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002272QualType
2273ASTContext::getFunctionType(QualType ResultTy,
2274 const QualType *ArgArray, unsigned NumArgs,
2275 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002276 // Unique functions, to guarantee there is only one function of a particular
2277 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002278 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002279 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002280
2281 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002282 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002283 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002284 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002285
2286 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002287 bool isCanonical =
2288 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2289 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002290 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002291 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002292 isCanonical = false;
2293
Roman Divacky65b88cd2011-03-01 17:40:53 +00002294 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2295 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2296 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002297
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002298 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002299 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002300 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002301 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002302 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002303 CanonicalArgs.reserve(NumArgs);
2304 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002305 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002306
John McCalldb40c7f2010-12-14 08:05:40 +00002307 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002308 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002309 CanonicalEPI.ExceptionSpecType = EST_None;
2310 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002311 CanonicalEPI.ExtInfo
2312 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2313
Chris Lattner76a00cf2008-04-06 22:59:24 +00002314 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002315 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002316 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002317
Chris Lattnerfd4de792007-01-27 01:15:32 +00002318 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002319 FunctionProtoType *NewIP =
2320 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002321 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002322 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002323
John McCall31168b02011-06-15 23:02:42 +00002324 // FunctionProtoType objects are allocated with extra bytes after
2325 // them for three variable size arrays at the end:
2326 // - parameter types
2327 // - exception types
2328 // - consumed-arguments flags
2329 // Instead of the exception types, there could be a noexcept
2330 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002331 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002332 NumArgs * sizeof(QualType);
2333 if (EPI.ExceptionSpecType == EST_Dynamic)
2334 Size += EPI.NumExceptions * sizeof(QualType);
2335 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002336 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002337 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002338 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002339 }
John McCall31168b02011-06-15 23:02:42 +00002340 if (EPI.ConsumedArguments)
2341 Size += NumArgs * sizeof(bool);
2342
John McCalldb40c7f2010-12-14 08:05:40 +00002343 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002344 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2345 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002346 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002347 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002348 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002349 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002350}
Chris Lattneref51c202006-11-10 07:17:23 +00002351
John McCalle78aac42010-03-10 03:28:59 +00002352#ifndef NDEBUG
2353static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2354 if (!isa<CXXRecordDecl>(D)) return false;
2355 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2356 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2357 return true;
2358 if (RD->getDescribedClassTemplate() &&
2359 !isa<ClassTemplateSpecializationDecl>(RD))
2360 return true;
2361 return false;
2362}
2363#endif
2364
2365/// getInjectedClassNameType - Return the unique reference to the
2366/// injected class name type for the specified templated declaration.
2367QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002368 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002369 assert(NeedsInjectedClassNameType(Decl));
2370 if (Decl->TypeForDecl) {
2371 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002372 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002373 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2374 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2375 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2376 } else {
John McCall424cec92011-01-19 06:33:43 +00002377 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002378 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002379 Decl->TypeForDecl = newType;
2380 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002381 }
2382 return QualType(Decl->TypeForDecl, 0);
2383}
2384
Douglas Gregor83a586e2008-04-13 21:07:44 +00002385/// getTypeDeclType - Return the unique reference to the type for the
2386/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002387QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002388 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002389 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002390
Richard Smithdda56e42011-04-15 14:24:37 +00002391 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002392 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002393
John McCall96f0b5f2010-03-10 06:48:02 +00002394 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2395 "Template type parameter types are always available.");
2396
John McCall81e38502010-02-16 03:57:14 +00002397 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002398 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002399 "struct/union has previous declaration");
2400 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002401 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002402 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002403 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002404 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002405 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002406 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002407 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002408 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2409 Decl->TypeForDecl = newType;
2410 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002411 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002412 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002413
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002414 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002415}
2416
Chris Lattner32d920b2007-01-26 02:01:53 +00002417/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002418/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002419QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002420ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2421 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002422 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002423
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002424 if (Canonical.isNull())
2425 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002426 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002427 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002428 Decl->TypeForDecl = newType;
2429 Types.push_back(newType);
2430 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002431}
2432
Jay Foad39c79802011-01-12 09:06:06 +00002433QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002434 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2435
Douglas Gregorec9fd132012-01-14 16:38:05 +00002436 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002437 if (PrevDecl->TypeForDecl)
2438 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2439
John McCall424cec92011-01-19 06:33:43 +00002440 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2441 Decl->TypeForDecl = newType;
2442 Types.push_back(newType);
2443 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002444}
2445
Jay Foad39c79802011-01-12 09:06:06 +00002446QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002447 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2448
Douglas Gregorec9fd132012-01-14 16:38:05 +00002449 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002450 if (PrevDecl->TypeForDecl)
2451 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2452
John McCall424cec92011-01-19 06:33:43 +00002453 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2454 Decl->TypeForDecl = newType;
2455 Types.push_back(newType);
2456 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002457}
2458
John McCall81904512011-01-06 01:58:22 +00002459QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2460 QualType modifiedType,
2461 QualType equivalentType) {
2462 llvm::FoldingSetNodeID id;
2463 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2464
2465 void *insertPos = 0;
2466 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2467 if (type) return QualType(type, 0);
2468
2469 QualType canon = getCanonicalType(equivalentType);
2470 type = new (*this, TypeAlignment)
2471 AttributedType(canon, attrKind, modifiedType, equivalentType);
2472
2473 Types.push_back(type);
2474 AttributedTypes.InsertNode(type, insertPos);
2475
2476 return QualType(type, 0);
2477}
2478
2479
John McCallcebee162009-10-18 09:09:24 +00002480/// \brief Retrieve a substitution-result type.
2481QualType
2482ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002483 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002484 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002485 && "replacement types must always be canonical");
2486
2487 llvm::FoldingSetNodeID ID;
2488 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2489 void *InsertPos = 0;
2490 SubstTemplateTypeParmType *SubstParm
2491 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2492
2493 if (!SubstParm) {
2494 SubstParm = new (*this, TypeAlignment)
2495 SubstTemplateTypeParmType(Parm, Replacement);
2496 Types.push_back(SubstParm);
2497 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2498 }
2499
2500 return QualType(SubstParm, 0);
2501}
2502
Douglas Gregorada4b792011-01-14 02:55:32 +00002503/// \brief Retrieve a
2504QualType ASTContext::getSubstTemplateTypeParmPackType(
2505 const TemplateTypeParmType *Parm,
2506 const TemplateArgument &ArgPack) {
2507#ifndef NDEBUG
2508 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2509 PEnd = ArgPack.pack_end();
2510 P != PEnd; ++P) {
2511 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2512 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2513 }
2514#endif
2515
2516 llvm::FoldingSetNodeID ID;
2517 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2518 void *InsertPos = 0;
2519 if (SubstTemplateTypeParmPackType *SubstParm
2520 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2521 return QualType(SubstParm, 0);
2522
2523 QualType Canon;
2524 if (!Parm->isCanonicalUnqualified()) {
2525 Canon = getCanonicalType(QualType(Parm, 0));
2526 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2527 ArgPack);
2528 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2529 }
2530
2531 SubstTemplateTypeParmPackType *SubstParm
2532 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2533 ArgPack);
2534 Types.push_back(SubstParm);
2535 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2536 return QualType(SubstParm, 0);
2537}
2538
Douglas Gregoreff93e02009-02-05 23:33:38 +00002539/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002540/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002541/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002542QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002543 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002544 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002545 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002546 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002547 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002548 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002549 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2550
2551 if (TypeParm)
2552 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Chandler Carruth08836322011-05-01 00:51:33 +00002554 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002555 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002556 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002557
2558 TemplateTypeParmType *TypeCheck
2559 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2560 assert(!TypeCheck && "Template type parameter canonical type broken");
2561 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002562 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002563 TypeParm = new (*this, TypeAlignment)
2564 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002565
2566 Types.push_back(TypeParm);
2567 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2568
2569 return QualType(TypeParm, 0);
2570}
2571
John McCalle78aac42010-03-10 03:28:59 +00002572TypeSourceInfo *
2573ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2574 SourceLocation NameLoc,
2575 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002576 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002577 assert(!Name.getAsDependentTemplateName() &&
2578 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002579 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002580
2581 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2582 TemplateSpecializationTypeLoc TL
2583 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002584 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002585 TL.setTemplateNameLoc(NameLoc);
2586 TL.setLAngleLoc(Args.getLAngleLoc());
2587 TL.setRAngleLoc(Args.getRAngleLoc());
2588 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2589 TL.setArgLocInfo(i, Args[i].getLocInfo());
2590 return DI;
2591}
2592
Mike Stump11289f42009-09-09 15:08:12 +00002593QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002594ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002595 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002596 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002597 assert(!Template.getAsDependentTemplateName() &&
2598 "No dependent template names here!");
2599
John McCall6b51f282009-11-23 01:53:49 +00002600 unsigned NumArgs = Args.size();
2601
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002602 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002603 ArgVec.reserve(NumArgs);
2604 for (unsigned i = 0; i != NumArgs; ++i)
2605 ArgVec.push_back(Args[i].getArgument());
2606
John McCall2408e322010-04-27 00:57:59 +00002607 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002608 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002609}
2610
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002611#ifndef NDEBUG
2612static bool hasAnyPackExpansions(const TemplateArgument *Args,
2613 unsigned NumArgs) {
2614 for (unsigned I = 0; I != NumArgs; ++I)
2615 if (Args[I].isPackExpansion())
2616 return true;
2617
2618 return true;
2619}
2620#endif
2621
John McCall0ad16662009-10-29 08:12:44 +00002622QualType
2623ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002624 const TemplateArgument *Args,
2625 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002626 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002627 assert(!Template.getAsDependentTemplateName() &&
2628 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002629 // Look through qualified template names.
2630 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2631 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002632
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002633 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002634 Template.getAsTemplateDecl() &&
2635 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002636 QualType CanonType;
2637 if (!Underlying.isNull())
2638 CanonType = getCanonicalType(Underlying);
2639 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002640 // We can get here with an alias template when the specialization contains
2641 // a pack expansion that does not match up with a parameter pack.
2642 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2643 "Caller must compute aliased type");
2644 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002645 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2646 NumArgs);
2647 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002648
Douglas Gregora8e02e72009-07-28 23:00:59 +00002649 // Allocate the (non-canonical) template specialization type, but don't
2650 // try to unique it: these types typically have location information that
2651 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002652 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2653 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002654 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002655 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002656 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002657 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2658 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002659
Douglas Gregor8bf42052009-02-09 18:46:07 +00002660 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002661 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002662}
2663
Mike Stump11289f42009-09-09 15:08:12 +00002664QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002665ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2666 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002667 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002668 assert(!Template.getAsDependentTemplateName() &&
2669 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002670
Douglas Gregore29139c2011-03-03 17:04:51 +00002671 // Look through qualified template names.
2672 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2673 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002674
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002675 // Build the canonical template specialization type.
2676 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002677 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002678 CanonArgs.reserve(NumArgs);
2679 for (unsigned I = 0; I != NumArgs; ++I)
2680 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2681
2682 // Determine whether this canonical template specialization type already
2683 // exists.
2684 llvm::FoldingSetNodeID ID;
2685 TemplateSpecializationType::Profile(ID, CanonTemplate,
2686 CanonArgs.data(), NumArgs, *this);
2687
2688 void *InsertPos = 0;
2689 TemplateSpecializationType *Spec
2690 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2691
2692 if (!Spec) {
2693 // Allocate a new canonical template specialization type.
2694 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2695 sizeof(TemplateArgument) * NumArgs),
2696 TypeAlignment);
2697 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2698 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002699 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002700 Types.push_back(Spec);
2701 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2702 }
2703
2704 assert(Spec->isDependentType() &&
2705 "Non-dependent template-id type must have a canonical type");
2706 return QualType(Spec, 0);
2707}
2708
2709QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002710ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2711 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002712 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002713 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002714 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002715
2716 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002717 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002718 if (T)
2719 return QualType(T, 0);
2720
Douglas Gregorc42075a2010-02-04 18:10:26 +00002721 QualType Canon = NamedType;
2722 if (!Canon.isCanonical()) {
2723 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002724 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2725 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002726 (void)CheckT;
2727 }
2728
Abramo Bagnara6150c882010-05-11 21:36:43 +00002729 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002730 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002731 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002732 return QualType(T, 0);
2733}
2734
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002735QualType
Jay Foad39c79802011-01-12 09:06:06 +00002736ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002737 llvm::FoldingSetNodeID ID;
2738 ParenType::Profile(ID, InnerType);
2739
2740 void *InsertPos = 0;
2741 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2742 if (T)
2743 return QualType(T, 0);
2744
2745 QualType Canon = InnerType;
2746 if (!Canon.isCanonical()) {
2747 Canon = getCanonicalType(InnerType);
2748 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2749 assert(!CheckT && "Paren canonical type broken");
2750 (void)CheckT;
2751 }
2752
2753 T = new (*this) ParenType(InnerType, Canon);
2754 Types.push_back(T);
2755 ParenTypes.InsertNode(T, InsertPos);
2756 return QualType(T, 0);
2757}
2758
Douglas Gregor02085352010-03-31 20:19:30 +00002759QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2760 NestedNameSpecifier *NNS,
2761 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002762 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002763 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2764
2765 if (Canon.isNull()) {
2766 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002767 ElaboratedTypeKeyword CanonKeyword = Keyword;
2768 if (Keyword == ETK_None)
2769 CanonKeyword = ETK_Typename;
2770
2771 if (CanonNNS != NNS || CanonKeyword != Keyword)
2772 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002773 }
2774
2775 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002776 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002777
2778 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002779 DependentNameType *T
2780 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002781 if (T)
2782 return QualType(T, 0);
2783
Douglas Gregor02085352010-03-31 20:19:30 +00002784 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002785 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002786 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002787 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002788}
2789
Mike Stump11289f42009-09-09 15:08:12 +00002790QualType
John McCallc392f372010-06-11 00:33:02 +00002791ASTContext::getDependentTemplateSpecializationType(
2792 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002793 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002794 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002795 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002796 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002797 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002798 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2799 ArgCopy.push_back(Args[I].getArgument());
2800 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2801 ArgCopy.size(),
2802 ArgCopy.data());
2803}
2804
2805QualType
2806ASTContext::getDependentTemplateSpecializationType(
2807 ElaboratedTypeKeyword Keyword,
2808 NestedNameSpecifier *NNS,
2809 const IdentifierInfo *Name,
2810 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002811 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002812 assert((!NNS || NNS->isDependent()) &&
2813 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002814
Douglas Gregorc42075a2010-02-04 18:10:26 +00002815 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002816 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2817 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002818
2819 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002820 DependentTemplateSpecializationType *T
2821 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002822 if (T)
2823 return QualType(T, 0);
2824
John McCallc392f372010-06-11 00:33:02 +00002825 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002826
John McCallc392f372010-06-11 00:33:02 +00002827 ElaboratedTypeKeyword CanonKeyword = Keyword;
2828 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2829
2830 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002831 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002832 for (unsigned I = 0; I != NumArgs; ++I) {
2833 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2834 if (!CanonArgs[I].structurallyEquals(Args[I]))
2835 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002836 }
2837
John McCallc392f372010-06-11 00:33:02 +00002838 QualType Canon;
2839 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2840 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2841 Name, NumArgs,
2842 CanonArgs.data());
2843
2844 // Find the insert position again.
2845 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2846 }
2847
2848 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2849 sizeof(TemplateArgument) * NumArgs),
2850 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002851 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002852 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002853 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002854 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002855 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002856}
2857
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002858QualType ASTContext::getPackExpansionType(QualType Pattern,
2859 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002860 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002861 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002862
2863 assert(Pattern->containsUnexpandedParameterPack() &&
2864 "Pack expansions must expand one or more parameter packs");
2865 void *InsertPos = 0;
2866 PackExpansionType *T
2867 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2868 if (T)
2869 return QualType(T, 0);
2870
2871 QualType Canon;
2872 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002873 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002874
2875 // Find the insert position again.
2876 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2877 }
2878
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002879 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002880 Types.push_back(T);
2881 PackExpansionTypes.InsertNode(T, InsertPos);
2882 return QualType(T, 0);
2883}
2884
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002885/// CmpProtocolNames - Comparison predicate for sorting protocols
2886/// alphabetically.
2887static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2888 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002889 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002890}
2891
John McCall8b07ec22010-05-15 11:32:37 +00002892static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002893 unsigned NumProtocols) {
2894 if (NumProtocols == 0) return true;
2895
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002896 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2897 return false;
2898
John McCallfc93cf92009-10-22 22:37:11 +00002899 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002900 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2901 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002902 return false;
2903 return true;
2904}
2905
2906static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002907 unsigned &NumProtocols) {
2908 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002909
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002910 // Sort protocols, keyed by name.
2911 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2912
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002913 // Canonicalize.
2914 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2915 Protocols[I] = Protocols[I]->getCanonicalDecl();
2916
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002917 // Remove duplicates.
2918 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2919 NumProtocols = ProtocolsEnd-Protocols;
2920}
2921
John McCall8b07ec22010-05-15 11:32:37 +00002922QualType ASTContext::getObjCObjectType(QualType BaseType,
2923 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002924 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002925 // If the base type is an interface and there aren't any protocols
2926 // to add, then the interface type will do just fine.
2927 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2928 return BaseType;
2929
2930 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002931 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002932 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002933 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002934 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2935 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002936
John McCall8b07ec22010-05-15 11:32:37 +00002937 // Build the canonical type, which has the canonical base type and
2938 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002939 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002940 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2941 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2942 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002943 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002944 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002945 unsigned UniqueCount = NumProtocols;
2946
John McCallfc93cf92009-10-22 22:37:11 +00002947 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002948 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2949 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002950 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002951 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2952 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002953 }
2954
2955 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002956 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2957 }
2958
2959 unsigned Size = sizeof(ObjCObjectTypeImpl);
2960 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2961 void *Mem = Allocate(Size, TypeAlignment);
2962 ObjCObjectTypeImpl *T =
2963 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2964
2965 Types.push_back(T);
2966 ObjCObjectTypes.InsertNode(T, InsertPos);
2967 return QualType(T, 0);
2968}
2969
2970/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2971/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002972QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002973 llvm::FoldingSetNodeID ID;
2974 ObjCObjectPointerType::Profile(ID, ObjectT);
2975
2976 void *InsertPos = 0;
2977 if (ObjCObjectPointerType *QT =
2978 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2979 return QualType(QT, 0);
2980
2981 // Find the canonical object type.
2982 QualType Canonical;
2983 if (!ObjectT.isCanonical()) {
2984 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2985
2986 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002987 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2988 }
2989
Douglas Gregorf85bee62010-02-08 22:59:26 +00002990 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002991 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2992 ObjCObjectPointerType *QType =
2993 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002994
Steve Narofffb4330f2009-06-17 22:40:22 +00002995 Types.push_back(QType);
2996 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002997 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002998}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002999
Douglas Gregor1c283312010-08-11 12:19:30 +00003000/// getObjCInterfaceType - Return the unique reference to the type for the
3001/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003002QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3003 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003004 if (Decl->TypeForDecl)
3005 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003006
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003007 if (PrevDecl) {
3008 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3009 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3010 return QualType(PrevDecl->TypeForDecl, 0);
3011 }
3012
Douglas Gregor7671e532011-12-16 16:34:57 +00003013 // Prefer the definition, if there is one.
3014 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3015 Decl = Def;
3016
Douglas Gregor1c283312010-08-11 12:19:30 +00003017 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3018 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3019 Decl->TypeForDecl = T;
3020 Types.push_back(T);
3021 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003022}
3023
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003024/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3025/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003026/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003027/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003028/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003029QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003030 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003031 if (tofExpr->isTypeDependent()) {
3032 llvm::FoldingSetNodeID ID;
3033 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003034
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003035 void *InsertPos = 0;
3036 DependentTypeOfExprType *Canon
3037 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3038 if (Canon) {
3039 // We already have a "canonical" version of an identical, dependent
3040 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003041 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003042 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003043 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003044 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003045 Canon
3046 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003047 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3048 toe = Canon;
3049 }
3050 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003051 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003052 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003053 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003054 Types.push_back(toe);
3055 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003056}
3057
Steve Naroffa773cd52007-08-01 18:02:17 +00003058/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3059/// TypeOfType AST's. The only motivation to unique these nodes would be
3060/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003061/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003062/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003063QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003064 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003065 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003066 Types.push_back(tot);
3067 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003068}
3069
Anders Carlssonad6bd352009-06-24 21:24:56 +00003070
Anders Carlsson81df7b82009-06-24 19:06:50 +00003071/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3072/// DecltypeType AST's. The only motivation to unique these nodes would be
3073/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003074/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003075/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003076QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003077 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003078
3079 // C++0x [temp.type]p2:
3080 // If an expression e involves a template parameter, decltype(e) denotes a
3081 // unique dependent type. Two such decltype-specifiers refer to the same
3082 // type only if their expressions are equivalent (14.5.6.1).
3083 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003084 llvm::FoldingSetNodeID ID;
3085 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Douglas Gregora21f6c32009-07-30 23:36:40 +00003087 void *InsertPos = 0;
3088 DependentDecltypeType *Canon
3089 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3090 if (Canon) {
3091 // We already have a "canonical" version of an equivalent, dependent
3092 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003093 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003094 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003095 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003096 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003097 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003098 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3099 dt = Canon;
3100 }
3101 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003102 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3103 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003104 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003105 Types.push_back(dt);
3106 return QualType(dt, 0);
3107}
3108
Alexis Hunte852b102011-05-24 22:41:36 +00003109/// getUnaryTransformationType - We don't unique these, since the memory
3110/// savings are minimal and these are rare.
3111QualType ASTContext::getUnaryTransformType(QualType BaseType,
3112 QualType UnderlyingType,
3113 UnaryTransformType::UTTKind Kind)
3114 const {
3115 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003116 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3117 Kind,
3118 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003119 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003120 Types.push_back(Ty);
3121 return QualType(Ty, 0);
3122}
3123
Richard Smithb2bc2e62011-02-21 20:05:19 +00003124/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003125QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003126 void *InsertPos = 0;
3127 if (!DeducedType.isNull()) {
3128 // Look in the folding set for an existing type.
3129 llvm::FoldingSetNodeID ID;
3130 AutoType::Profile(ID, DeducedType);
3131 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3132 return QualType(AT, 0);
3133 }
3134
3135 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3136 Types.push_back(AT);
3137 if (InsertPos)
3138 AutoTypes.InsertNode(AT, InsertPos);
3139 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003140}
3141
Eli Friedman0dfb8892011-10-06 23:00:33 +00003142/// getAtomicType - Return the uniqued reference to the atomic type for
3143/// the given value type.
3144QualType ASTContext::getAtomicType(QualType T) const {
3145 // Unique pointers, to guarantee there is only one pointer of a particular
3146 // structure.
3147 llvm::FoldingSetNodeID ID;
3148 AtomicType::Profile(ID, T);
3149
3150 void *InsertPos = 0;
3151 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3152 return QualType(AT, 0);
3153
3154 // If the atomic value type isn't canonical, this won't be a canonical type
3155 // either, so fill in the canonical type field.
3156 QualType Canonical;
3157 if (!T.isCanonical()) {
3158 Canonical = getAtomicType(getCanonicalType(T));
3159
3160 // Get the new insert position for the node we care about.
3161 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3162 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3163 }
3164 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3165 Types.push_back(New);
3166 AtomicTypes.InsertNode(New, InsertPos);
3167 return QualType(New, 0);
3168}
3169
Richard Smith02e85f32011-04-14 22:09:26 +00003170/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3171QualType ASTContext::getAutoDeductType() const {
3172 if (AutoDeductTy.isNull())
3173 AutoDeductTy = getAutoType(QualType());
3174 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3175 return AutoDeductTy;
3176}
3177
3178/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3179QualType ASTContext::getAutoRRefDeductType() const {
3180 if (AutoRRefDeductTy.isNull())
3181 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3182 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3183 return AutoRRefDeductTy;
3184}
3185
Chris Lattnerfb072462007-01-23 05:45:31 +00003186/// getTagDeclType - Return the unique reference to the type for the
3187/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003188QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003189 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003190 // FIXME: What is the design on getTagDeclType when it requires casting
3191 // away const? mutable?
3192 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003193}
3194
Mike Stump11289f42009-09-09 15:08:12 +00003195/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3196/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3197/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003198CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003199 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003200}
Chris Lattnerfb072462007-01-23 05:45:31 +00003201
Hans Wennborg27541db2011-10-27 08:29:09 +00003202/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3203CanQualType ASTContext::getIntMaxType() const {
3204 return getFromTargetType(Target->getIntMaxType());
3205}
3206
3207/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3208CanQualType ASTContext::getUIntMaxType() const {
3209 return getFromTargetType(Target->getUIntMaxType());
3210}
3211
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003212/// getSignedWCharType - Return the type of "signed wchar_t".
3213/// Used when in C++, as a GCC extension.
3214QualType ASTContext::getSignedWCharType() const {
3215 // FIXME: derive from "Target" ?
3216 return WCharTy;
3217}
3218
3219/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3220/// Used when in C++, as a GCC extension.
3221QualType ASTContext::getUnsignedWCharType() const {
3222 // FIXME: derive from "Target" ?
3223 return UnsignedIntTy;
3224}
3225
Hans Wennborg27541db2011-10-27 08:29:09 +00003226/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003227/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3228QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003229 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003230}
3231
Chris Lattnera21ad802008-04-02 05:18:44 +00003232//===----------------------------------------------------------------------===//
3233// Type Operators
3234//===----------------------------------------------------------------------===//
3235
Jay Foad39c79802011-01-12 09:06:06 +00003236CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003237 // Push qualifiers into arrays, and then discard any remaining
3238 // qualifiers.
3239 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003240 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003241 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003242 QualType Result;
3243 if (isa<ArrayType>(Ty)) {
3244 Result = getArrayDecayedType(QualType(Ty,0));
3245 } else if (isa<FunctionType>(Ty)) {
3246 Result = getPointerType(QualType(Ty, 0));
3247 } else {
3248 Result = QualType(Ty, 0);
3249 }
3250
3251 return CanQualType::CreateUnsafe(Result);
3252}
3253
John McCall6c9dd522011-01-18 07:41:22 +00003254QualType ASTContext::getUnqualifiedArrayType(QualType type,
3255 Qualifiers &quals) {
3256 SplitQualType splitType = type.getSplitUnqualifiedType();
3257
3258 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3259 // the unqualified desugared type and then drops it on the floor.
3260 // We then have to strip that sugar back off with
3261 // getUnqualifiedDesugaredType(), which is silly.
3262 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003263 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003264
3265 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003266 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003267 quals = splitType.Quals;
3268 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003269 }
3270
John McCall6c9dd522011-01-18 07:41:22 +00003271 // Otherwise, recurse on the array's element type.
3272 QualType elementType = AT->getElementType();
3273 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3274
3275 // If that didn't change the element type, AT has no qualifiers, so we
3276 // can just use the results in splitType.
3277 if (elementType == unqualElementType) {
3278 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003279 quals = splitType.Quals;
3280 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003281 }
3282
3283 // Otherwise, add in the qualifiers from the outermost type, then
3284 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003285 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003286
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003287 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003288 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003289 CAT->getSizeModifier(), 0);
3290 }
3291
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003292 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003293 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003294 }
3295
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003296 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003297 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003298 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003299 VAT->getSizeModifier(),
3300 VAT->getIndexTypeCVRQualifiers(),
3301 VAT->getBracketsRange());
3302 }
3303
3304 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003305 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003306 DSAT->getSizeModifier(), 0,
3307 SourceRange());
3308}
3309
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003310/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3311/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3312/// they point to and return true. If T1 and T2 aren't pointer types
3313/// or pointer-to-member types, or if they are not similar at this
3314/// level, returns false and leaves T1 and T2 unchanged. Top-level
3315/// qualifiers on T1 and T2 are ignored. This function will typically
3316/// be called in a loop that successively "unwraps" pointer and
3317/// pointer-to-member types to compare them at each level.
3318bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3319 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3320 *T2PtrType = T2->getAs<PointerType>();
3321 if (T1PtrType && T2PtrType) {
3322 T1 = T1PtrType->getPointeeType();
3323 T2 = T2PtrType->getPointeeType();
3324 return true;
3325 }
3326
3327 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3328 *T2MPType = T2->getAs<MemberPointerType>();
3329 if (T1MPType && T2MPType &&
3330 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3331 QualType(T2MPType->getClass(), 0))) {
3332 T1 = T1MPType->getPointeeType();
3333 T2 = T2MPType->getPointeeType();
3334 return true;
3335 }
3336
David Blaikiebbafb8a2012-03-11 07:00:24 +00003337 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003338 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3339 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3340 if (T1OPType && T2OPType) {
3341 T1 = T1OPType->getPointeeType();
3342 T2 = T2OPType->getPointeeType();
3343 return true;
3344 }
3345 }
3346
3347 // FIXME: Block pointers, too?
3348
3349 return false;
3350}
3351
Jay Foad39c79802011-01-12 09:06:06 +00003352DeclarationNameInfo
3353ASTContext::getNameForTemplate(TemplateName Name,
3354 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003355 switch (Name.getKind()) {
3356 case TemplateName::QualifiedTemplate:
3357 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003358 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003359 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3360 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003361
John McCalld9dfe3a2011-06-30 08:33:18 +00003362 case TemplateName::OverloadedTemplate: {
3363 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3364 // DNInfo work in progress: CHECKME: what about DNLoc?
3365 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3366 }
3367
3368 case TemplateName::DependentTemplate: {
3369 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003370 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003371 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003372 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3373 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003374 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003375 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3376 // DNInfo work in progress: FIXME: source locations?
3377 DeclarationNameLoc DNLoc;
3378 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3379 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3380 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003381 }
3382 }
3383
John McCalld9dfe3a2011-06-30 08:33:18 +00003384 case TemplateName::SubstTemplateTemplateParm: {
3385 SubstTemplateTemplateParmStorage *subst
3386 = Name.getAsSubstTemplateTemplateParm();
3387 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3388 NameLoc);
3389 }
3390
3391 case TemplateName::SubstTemplateTemplateParmPack: {
3392 SubstTemplateTemplateParmPackStorage *subst
3393 = Name.getAsSubstTemplateTemplateParmPack();
3394 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3395 NameLoc);
3396 }
3397 }
3398
3399 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003400}
3401
Jay Foad39c79802011-01-12 09:06:06 +00003402TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003403 switch (Name.getKind()) {
3404 case TemplateName::QualifiedTemplate:
3405 case TemplateName::Template: {
3406 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003407 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003408 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003409 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3410
3411 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003412 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003413 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003414
John McCalld9dfe3a2011-06-30 08:33:18 +00003415 case TemplateName::OverloadedTemplate:
3416 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003417
John McCalld9dfe3a2011-06-30 08:33:18 +00003418 case TemplateName::DependentTemplate: {
3419 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3420 assert(DTN && "Non-dependent template names must refer to template decls.");
3421 return DTN->CanonicalTemplateName;
3422 }
3423
3424 case TemplateName::SubstTemplateTemplateParm: {
3425 SubstTemplateTemplateParmStorage *subst
3426 = Name.getAsSubstTemplateTemplateParm();
3427 return getCanonicalTemplateName(subst->getReplacement());
3428 }
3429
3430 case TemplateName::SubstTemplateTemplateParmPack: {
3431 SubstTemplateTemplateParmPackStorage *subst
3432 = Name.getAsSubstTemplateTemplateParmPack();
3433 TemplateTemplateParmDecl *canonParameter
3434 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3435 TemplateArgument canonArgPack
3436 = getCanonicalTemplateArgument(subst->getArgumentPack());
3437 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3438 }
3439 }
3440
3441 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003442}
3443
Douglas Gregoradee3e32009-11-11 23:06:43 +00003444bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3445 X = getCanonicalTemplateName(X);
3446 Y = getCanonicalTemplateName(Y);
3447 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3448}
3449
Mike Stump11289f42009-09-09 15:08:12 +00003450TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003451ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003452 switch (Arg.getKind()) {
3453 case TemplateArgument::Null:
3454 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003455
Douglas Gregora8e02e72009-07-28 23:00:59 +00003456 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003457 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003459 case TemplateArgument::Declaration: {
3460 if (Decl *D = Arg.getAsDecl())
3461 return TemplateArgument(D->getCanonicalDecl());
3462 return TemplateArgument((Decl*)0);
3463 }
Mike Stump11289f42009-09-09 15:08:12 +00003464
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003465 case TemplateArgument::Template:
3466 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003467
3468 case TemplateArgument::TemplateExpansion:
3469 return TemplateArgument(getCanonicalTemplateName(
3470 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003471 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003472
Douglas Gregora8e02e72009-07-28 23:00:59 +00003473 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003474 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003475
Douglas Gregora8e02e72009-07-28 23:00:59 +00003476 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003477 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003478
Douglas Gregora8e02e72009-07-28 23:00:59 +00003479 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003480 if (Arg.pack_size() == 0)
3481 return Arg;
3482
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003483 TemplateArgument *CanonArgs
3484 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003485 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003486 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003487 AEnd = Arg.pack_end();
3488 A != AEnd; (void)++A, ++Idx)
3489 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003490
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003491 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003492 }
3493 }
3494
3495 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003496 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003497}
3498
Douglas Gregor333489b2009-03-27 23:10:48 +00003499NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003500ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003501 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003502 return 0;
3503
3504 switch (NNS->getKind()) {
3505 case NestedNameSpecifier::Identifier:
3506 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003507 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003508 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3509 NNS->getAsIdentifier());
3510
3511 case NestedNameSpecifier::Namespace:
3512 // A namespace is canonical; build a nested-name-specifier with
3513 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003514 return NestedNameSpecifier::Create(*this, 0,
3515 NNS->getAsNamespace()->getOriginalNamespace());
3516
3517 case NestedNameSpecifier::NamespaceAlias:
3518 // A namespace is canonical; build a nested-name-specifier with
3519 // this namespace and no prefix.
3520 return NestedNameSpecifier::Create(*this, 0,
3521 NNS->getAsNamespaceAlias()->getNamespace()
3522 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003523
3524 case NestedNameSpecifier::TypeSpec:
3525 case NestedNameSpecifier::TypeSpecWithTemplate: {
3526 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003527
3528 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3529 // break it apart into its prefix and identifier, then reconsititute those
3530 // as the canonical nested-name-specifier. This is required to canonicalize
3531 // a dependent nested-name-specifier involving typedefs of dependent-name
3532 // types, e.g.,
3533 // typedef typename T::type T1;
3534 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003535 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3536 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003537 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003538
Eli Friedman5358a0a2012-03-03 04:09:56 +00003539 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3540 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3541 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003542 return NestedNameSpecifier::Create(*this, 0, false,
3543 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003544 }
3545
3546 case NestedNameSpecifier::Global:
3547 // The global specifier is canonical and unique.
3548 return NNS;
3549 }
3550
David Blaikie8a40f702012-01-17 06:56:22 +00003551 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003552}
3553
Chris Lattner7adf0762008-08-04 07:31:14 +00003554
Jay Foad39c79802011-01-12 09:06:06 +00003555const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003556 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003557 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003558 // Handle the common positive case fast.
3559 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3560 return AT;
3561 }
Mike Stump11289f42009-09-09 15:08:12 +00003562
John McCall8ccfcb52009-09-24 19:53:00 +00003563 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003564 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003565 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003566
John McCall8ccfcb52009-09-24 19:53:00 +00003567 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003568 // implements C99 6.7.3p8: "If the specification of an array type includes
3569 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003570
Chris Lattner7adf0762008-08-04 07:31:14 +00003571 // If we get here, we either have type qualifiers on the type, or we have
3572 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003573 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003574
John McCall33ddac02011-01-19 10:06:00 +00003575 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003576 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003577
Chris Lattner7adf0762008-08-04 07:31:14 +00003578 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003579 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003580 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003581 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003582
Chris Lattner7adf0762008-08-04 07:31:14 +00003583 // Otherwise, we have an array and we have qualifiers on it. Push the
3584 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003585 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003586
Chris Lattner7adf0762008-08-04 07:31:14 +00003587 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3588 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3589 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003590 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003591 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3592 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3593 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003594 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003595
Mike Stump11289f42009-09-09 15:08:12 +00003596 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003597 = dyn_cast<DependentSizedArrayType>(ATy))
3598 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003599 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003600 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003601 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003602 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003603 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattner7adf0762008-08-04 07:31:14 +00003605 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003606 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003607 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003608 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003609 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003610 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003611}
3612
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003613QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003614 // C99 6.7.5.3p7:
3615 // A declaration of a parameter as "array of type" shall be
3616 // adjusted to "qualified pointer to type", where the type
3617 // qualifiers (if any) are those specified within the [ and ] of
3618 // the array type derivation.
3619 if (T->isArrayType())
3620 return getArrayDecayedType(T);
3621
3622 // C99 6.7.5.3p8:
3623 // A declaration of a parameter as "function returning type"
3624 // shall be adjusted to "pointer to function returning type", as
3625 // in 6.3.2.1.
3626 if (T->isFunctionType())
3627 return getPointerType(T);
3628
3629 return T;
3630}
3631
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003632QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003633 T = getVariableArrayDecayedType(T);
3634 T = getAdjustedParameterType(T);
3635 return T.getUnqualifiedType();
3636}
3637
Chris Lattnera21ad802008-04-02 05:18:44 +00003638/// getArrayDecayedType - Return the properly qualified result of decaying the
3639/// specified array type to a pointer. This operation is non-trivial when
3640/// handling typedefs etc. The canonical type of "T" must be an array type,
3641/// this returns a pointer to a properly qualified element of the array.
3642///
3643/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003644QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003645 // Get the element type with 'getAsArrayType' so that we don't lose any
3646 // typedefs in the element type of the array. This also handles propagation
3647 // of type qualifiers from the array type into the element type if present
3648 // (C99 6.7.3p8).
3649 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3650 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003651
Chris Lattner7adf0762008-08-04 07:31:14 +00003652 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003653
3654 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003655 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003656}
3657
John McCall33ddac02011-01-19 10:06:00 +00003658QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3659 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003660}
3661
John McCall33ddac02011-01-19 10:06:00 +00003662QualType ASTContext::getBaseElementType(QualType type) const {
3663 Qualifiers qs;
3664 while (true) {
3665 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003666 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003667 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003668
John McCall33ddac02011-01-19 10:06:00 +00003669 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003670 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
John McCall33ddac02011-01-19 10:06:00 +00003673 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003674}
3675
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003676/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003677uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003678ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3679 uint64_t ElementCount = 1;
3680 do {
3681 ElementCount *= CA->getSize().getZExtValue();
3682 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3683 } while (CA);
3684 return ElementCount;
3685}
3686
Steve Naroff0af91202007-04-27 21:51:21 +00003687/// getFloatingRank - Return a relative rank for floating point types.
3688/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003689static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003690 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003691 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003692
John McCall9dd450b2009-09-21 23:43:11 +00003693 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3694 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003695 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003696 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003697 case BuiltinType::Float: return FloatRank;
3698 case BuiltinType::Double: return DoubleRank;
3699 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003700 }
3701}
3702
Mike Stump11289f42009-09-09 15:08:12 +00003703/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3704/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003705/// 'typeDomain' is a real floating point or complex type.
3706/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003707QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3708 QualType Domain) const {
3709 FloatingRank EltRank = getFloatingRank(Size);
3710 if (Domain->isComplexType()) {
3711 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003712 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003713 case FloatRank: return FloatComplexTy;
3714 case DoubleRank: return DoubleComplexTy;
3715 case LongDoubleRank: return LongDoubleComplexTy;
3716 }
Steve Naroff0af91202007-04-27 21:51:21 +00003717 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003718
3719 assert(Domain->isRealFloatingType() && "Unknown domain!");
3720 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003721 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003722 case FloatRank: return FloatTy;
3723 case DoubleRank: return DoubleTy;
3724 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003725 }
David Blaikief47fa302012-01-17 02:30:50 +00003726 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003727}
3728
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003729/// getFloatingTypeOrder - Compare the rank of the two specified floating
3730/// point types, ignoring the domain of the type (i.e. 'double' ==
3731/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003732/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003733int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003734 FloatingRank LHSR = getFloatingRank(LHS);
3735 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003736
Chris Lattnerb90739d2008-04-06 23:38:49 +00003737 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003738 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003739 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003740 return 1;
3741 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003742}
3743
Chris Lattner76a00cf2008-04-06 22:59:24 +00003744/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3745/// routine will assert if passed a built-in type that isn't an integer or enum,
3746/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003747unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003748 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003749
Chris Lattner76a00cf2008-04-06 22:59:24 +00003750 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003751 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003752 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003753 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003754 case BuiltinType::Char_S:
3755 case BuiltinType::Char_U:
3756 case BuiltinType::SChar:
3757 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003758 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003759 case BuiltinType::Short:
3760 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003761 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003762 case BuiltinType::Int:
3763 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003764 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003765 case BuiltinType::Long:
3766 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003767 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003768 case BuiltinType::LongLong:
3769 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003770 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003771 case BuiltinType::Int128:
3772 case BuiltinType::UInt128:
3773 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003774 }
3775}
3776
Eli Friedman629ffb92009-08-20 04:21:42 +00003777/// \brief Whether this is a promotable bitfield reference according
3778/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3779///
3780/// \returns the type this bit-field will promote to, or NULL if no
3781/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003782QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003783 if (E->isTypeDependent() || E->isValueDependent())
3784 return QualType();
3785
Eli Friedman629ffb92009-08-20 04:21:42 +00003786 FieldDecl *Field = E->getBitField();
3787 if (!Field)
3788 return QualType();
3789
3790 QualType FT = Field->getType();
3791
Richard Smithcaf33902011-10-10 18:28:20 +00003792 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003793 uint64_t IntSize = getTypeSize(IntTy);
3794 // GCC extension compatibility: if the bit-field size is less than or equal
3795 // to the size of int, it gets promoted no matter what its type is.
3796 // For instance, unsigned long bf : 4 gets promoted to signed int.
3797 if (BitWidth < IntSize)
3798 return IntTy;
3799
3800 if (BitWidth == IntSize)
3801 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3802
3803 // Types bigger than int are not subject to promotions, and therefore act
3804 // like the base type.
3805 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3806 // is ridiculous.
3807 return QualType();
3808}
3809
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003810/// getPromotedIntegerType - Returns the type that Promotable will
3811/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3812/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003813QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003814 assert(!Promotable.isNull());
3815 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003816 if (const EnumType *ET = Promotable->getAs<EnumType>())
3817 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003818
3819 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3820 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3821 // (3.9.1) can be converted to a prvalue of the first of the following
3822 // types that can represent all the values of its underlying type:
3823 // int, unsigned int, long int, unsigned long int, long long int, or
3824 // unsigned long long int [...]
3825 // FIXME: Is there some better way to compute this?
3826 if (BT->getKind() == BuiltinType::WChar_S ||
3827 BT->getKind() == BuiltinType::WChar_U ||
3828 BT->getKind() == BuiltinType::Char16 ||
3829 BT->getKind() == BuiltinType::Char32) {
3830 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3831 uint64_t FromSize = getTypeSize(BT);
3832 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3833 LongLongTy, UnsignedLongLongTy };
3834 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3835 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3836 if (FromSize < ToSize ||
3837 (FromSize == ToSize &&
3838 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3839 return PromoteTypes[Idx];
3840 }
3841 llvm_unreachable("char type should fit into long long");
3842 }
3843 }
3844
3845 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003846 if (Promotable->isSignedIntegerType())
3847 return IntTy;
3848 uint64_t PromotableSize = getTypeSize(Promotable);
3849 uint64_t IntSize = getTypeSize(IntTy);
3850 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3851 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3852}
3853
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003854/// \brief Recurses in pointer/array types until it finds an objc retainable
3855/// type and returns its ownership.
3856Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3857 while (!T.isNull()) {
3858 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3859 return T.getObjCLifetime();
3860 if (T->isArrayType())
3861 T = getBaseElementType(T);
3862 else if (const PointerType *PT = T->getAs<PointerType>())
3863 T = PT->getPointeeType();
3864 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003865 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003866 else
3867 break;
3868 }
3869
3870 return Qualifiers::OCL_None;
3871}
3872
Mike Stump11289f42009-09-09 15:08:12 +00003873/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003874/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003875/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003876int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003877 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3878 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003879 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003880
Chris Lattner76a00cf2008-04-06 22:59:24 +00003881 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3882 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003883
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003884 unsigned LHSRank = getIntegerRank(LHSC);
3885 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003886
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003887 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3888 if (LHSRank == RHSRank) return 0;
3889 return LHSRank > RHSRank ? 1 : -1;
3890 }
Mike Stump11289f42009-09-09 15:08:12 +00003891
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003892 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3893 if (LHSUnsigned) {
3894 // If the unsigned [LHS] type is larger, return it.
3895 if (LHSRank >= RHSRank)
3896 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003897
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003898 // If the signed type can represent all values of the unsigned type, it
3899 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003900 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003901 return -1;
3902 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003903
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003904 // If the unsigned [RHS] type is larger, return it.
3905 if (RHSRank >= LHSRank)
3906 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003907
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003908 // If the signed type can represent all values of the unsigned type, it
3909 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003910 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003911 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003912}
Anders Carlsson98f07902007-08-17 05:31:46 +00003913
Anders Carlsson6d417272009-11-14 21:45:58 +00003914static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003915CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3916 DeclContext *DC, IdentifierInfo *Id) {
3917 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003918 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003919 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003920 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003921 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003922}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003923
Mike Stump11289f42009-09-09 15:08:12 +00003924// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003925QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003926 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003927 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003928 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003929 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003930 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003931
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003932 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003933
Anders Carlsson98f07902007-08-17 05:31:46 +00003934 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003935 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003936 // int flags;
3937 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003938 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003939 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003940 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003941 FieldTypes[3] = LongTy;
3942
Anders Carlsson98f07902007-08-17 05:31:46 +00003943 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003944 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003945 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003946 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003947 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003948 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003949 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003950 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003951 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003952 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003953 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003954 }
3955
Douglas Gregord5058122010-02-11 01:19:42 +00003956 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003957 }
Mike Stump11289f42009-09-09 15:08:12 +00003958
Anders Carlsson98f07902007-08-17 05:31:46 +00003959 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003960}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003961
Douglas Gregor512b0772009-04-23 22:29:11 +00003962void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003963 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003964 assert(Rec && "Invalid CFConstantStringType");
3965 CFConstantStringTypeDecl = Rec->getDecl();
3966}
3967
Jay Foad39c79802011-01-12 09:06:06 +00003968QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003969 if (BlockDescriptorType)
3970 return getTagDeclType(BlockDescriptorType);
3971
3972 RecordDecl *T;
3973 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003974 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003975 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003976 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003977
3978 QualType FieldTypes[] = {
3979 UnsignedLongTy,
3980 UnsignedLongTy,
3981 };
3982
3983 const char *FieldNames[] = {
3984 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003985 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003986 };
3987
3988 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003989 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003990 SourceLocation(),
3991 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003992 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003993 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003994 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003995 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003996 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003997 T->addDecl(Field);
3998 }
3999
Douglas Gregord5058122010-02-11 01:19:42 +00004000 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004001
4002 BlockDescriptorType = T;
4003
4004 return getTagDeclType(BlockDescriptorType);
4005}
4006
Jay Foad39c79802011-01-12 09:06:06 +00004007QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004008 if (BlockDescriptorExtendedType)
4009 return getTagDeclType(BlockDescriptorExtendedType);
4010
4011 RecordDecl *T;
4012 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004013 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004014 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004015 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004016
4017 QualType FieldTypes[] = {
4018 UnsignedLongTy,
4019 UnsignedLongTy,
4020 getPointerType(VoidPtrTy),
4021 getPointerType(VoidPtrTy)
4022 };
4023
4024 const char *FieldNames[] = {
4025 "reserved",
4026 "Size",
4027 "CopyFuncPtr",
4028 "DestroyFuncPtr"
4029 };
4030
4031 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004032 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004033 SourceLocation(),
4034 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004035 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004036 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004037 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004038 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004039 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004040 T->addDecl(Field);
4041 }
4042
Douglas Gregord5058122010-02-11 01:19:42 +00004043 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004044
4045 BlockDescriptorExtendedType = T;
4046
4047 return getTagDeclType(BlockDescriptorExtendedType);
4048}
4049
Jay Foad39c79802011-01-12 09:06:06 +00004050bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004051 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004052 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004053 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004054 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4055 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004056 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004057
4058 }
4059 }
Mike Stump94967902009-10-21 18:16:27 +00004060 return false;
4061}
4062
Jay Foad39c79802011-01-12 09:06:06 +00004063QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004064ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004065 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004066 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004067 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004068 // unsigned int __flags;
4069 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004070 // void *__copy_helper; // as needed
4071 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004072 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004073 // } *
4074
Mike Stump94967902009-10-21 18:16:27 +00004075 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4076
4077 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004078 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004079 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4080 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004081 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004082 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004083 T->startDefinition();
4084 QualType Int32Ty = IntTy;
4085 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4086 QualType FieldTypes[] = {
4087 getPointerType(VoidPtrTy),
4088 getPointerType(getTagDeclType(T)),
4089 Int32Ty,
4090 Int32Ty,
4091 getPointerType(VoidPtrTy),
4092 getPointerType(VoidPtrTy),
4093 Ty
4094 };
4095
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004096 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004097 "__isa",
4098 "__forwarding",
4099 "__flags",
4100 "__size",
4101 "__copy_helper",
4102 "__destroy_helper",
4103 DeclName,
4104 };
4105
4106 for (size_t i = 0; i < 7; ++i) {
4107 if (!HasCopyAndDispose && i >=4 && i <= 5)
4108 continue;
4109 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004110 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004111 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004112 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004113 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004114 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004115 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004116 T->addDecl(Field);
4117 }
4118
Douglas Gregord5058122010-02-11 01:19:42 +00004119 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004120
4121 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004122}
4123
Douglas Gregorbab8a962011-09-08 01:46:34 +00004124TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4125 if (!ObjCInstanceTypeDecl)
4126 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4127 getTranslationUnitDecl(),
4128 SourceLocation(),
4129 SourceLocation(),
4130 &Idents.get("instancetype"),
4131 getTrivialTypeSourceInfo(getObjCIdType()));
4132 return ObjCInstanceTypeDecl;
4133}
4134
Anders Carlsson18acd442007-10-29 06:33:42 +00004135// This returns true if a type has been typedefed to BOOL:
4136// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004137static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004138 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004139 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4140 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004141
Anders Carlssond8499822007-10-29 05:01:08 +00004142 return false;
4143}
4144
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004145/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004146/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004147CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004148 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4149 return CharUnits::Zero();
4150
Ken Dyck40775002010-01-11 17:06:35 +00004151 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004152
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004153 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004154 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004155 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004156 // Treat arrays as pointers, since that's how they're passed in.
4157 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004158 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004159 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004160}
4161
4162static inline
4163std::string charUnitsToString(const CharUnits &CU) {
4164 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004165}
4166
John McCall351762c2011-02-07 10:33:21 +00004167/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004168/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004169std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4170 std::string S;
4171
David Chisnall950a9512009-11-17 19:33:30 +00004172 const BlockDecl *Decl = Expr->getBlockDecl();
4173 QualType BlockTy =
4174 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4175 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004176 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004177 // Compute size of all parameters.
4178 // Start with computing size of a pointer in number of bytes.
4179 // FIXME: There might(should) be a better way of doing this computation!
4180 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004181 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4182 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004183 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004184 E = Decl->param_end(); PI != E; ++PI) {
4185 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004186 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004187 if (sz.isZero())
4188 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004189 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004190 ParmOffset += sz;
4191 }
4192 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004193 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004194 // Block pointer and offset.
4195 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004196
4197 // Argument types.
4198 ParmOffset = PtrSize;
4199 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4200 Decl->param_end(); PI != E; ++PI) {
4201 ParmVarDecl *PVDecl = *PI;
4202 QualType PType = PVDecl->getOriginalType();
4203 if (const ArrayType *AT =
4204 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4205 // Use array's original type only if it has known number of
4206 // elements.
4207 if (!isa<ConstantArrayType>(AT))
4208 PType = PVDecl->getType();
4209 } else if (PType->isFunctionType())
4210 PType = PVDecl->getType();
4211 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004212 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004213 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004214 }
John McCall351762c2011-02-07 10:33:21 +00004215
4216 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004217}
4218
Douglas Gregora9d84932011-05-27 01:19:52 +00004219bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004220 std::string& S) {
4221 // Encode result type.
4222 getObjCEncodingForType(Decl->getResultType(), S);
4223 CharUnits ParmOffset;
4224 // Compute size of all parameters.
4225 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4226 E = Decl->param_end(); PI != E; ++PI) {
4227 QualType PType = (*PI)->getType();
4228 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004229 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004230 continue;
4231
David Chisnall50e4eba2010-12-30 14:05:53 +00004232 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004233 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004234 ParmOffset += sz;
4235 }
4236 S += charUnitsToString(ParmOffset);
4237 ParmOffset = CharUnits::Zero();
4238
4239 // Argument types.
4240 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4241 E = Decl->param_end(); PI != E; ++PI) {
4242 ParmVarDecl *PVDecl = *PI;
4243 QualType PType = PVDecl->getOriginalType();
4244 if (const ArrayType *AT =
4245 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4246 // Use array's original type only if it has known number of
4247 // elements.
4248 if (!isa<ConstantArrayType>(AT))
4249 PType = PVDecl->getType();
4250 } else if (PType->isFunctionType())
4251 PType = PVDecl->getType();
4252 getObjCEncodingForType(PType, S);
4253 S += charUnitsToString(ParmOffset);
4254 ParmOffset += getObjCEncodingTypeSize(PType);
4255 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004256
4257 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004258}
4259
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004260/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4261/// method parameter or return type. If Extended, include class names and
4262/// block object types.
4263void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4264 QualType T, std::string& S,
4265 bool Extended) const {
4266 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4267 getObjCEncodingForTypeQualifier(QT, S);
4268 // Encode parameter type.
4269 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4270 true /*OutermostType*/,
4271 false /*EncodingProperty*/,
4272 false /*StructField*/,
4273 Extended /*EncodeBlockParameters*/,
4274 Extended /*EncodeClassNames*/);
4275}
4276
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004277/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004278/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004279bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004280 std::string& S,
4281 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004282 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004283 // Encode return type.
4284 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4285 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004286 // Compute size of all parameters.
4287 // Start with computing size of a pointer in number of bytes.
4288 // FIXME: There might(should) be a better way of doing this computation!
4289 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004290 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004291 // The first two arguments (self and _cmd) are pointers; account for
4292 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004293 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004294 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004295 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004296 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004297 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004298 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004299 continue;
4300
Ken Dyck40775002010-01-11 17:06:35 +00004301 assert (sz.isPositive() &&
4302 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004303 ParmOffset += sz;
4304 }
Ken Dyck40775002010-01-11 17:06:35 +00004305 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004306 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004307 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004308
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004309 // Argument types.
4310 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004311 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004312 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004313 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004314 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004315 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004316 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4317 // Use array's original type only if it has known number of
4318 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004319 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004320 PType = PVDecl->getType();
4321 } else if (PType->isFunctionType())
4322 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004323 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4324 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004325 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004326 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004327 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004328
4329 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004330}
4331
Daniel Dunbar4932b362008-08-28 04:38:10 +00004332/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004333/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004334/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4335/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004336/// Property attributes are stored as a comma-delimited C string. The simple
4337/// attributes readonly and bycopy are encoded as single characters. The
4338/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4339/// encoded as single characters, followed by an identifier. Property types
4340/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004341/// these attributes are defined by the following enumeration:
4342/// @code
4343/// enum PropertyAttributes {
4344/// kPropertyReadOnly = 'R', // property is read-only.
4345/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4346/// kPropertyByref = '&', // property is a reference to the value last assigned
4347/// kPropertyDynamic = 'D', // property is dynamic
4348/// kPropertyGetter = 'G', // followed by getter selector name
4349/// kPropertySetter = 'S', // followed by setter selector name
4350/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004351/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004352/// kPropertyWeak = 'W' // 'weak' property
4353/// kPropertyStrong = 'P' // property GC'able
4354/// kPropertyNonAtomic = 'N' // property non-atomic
4355/// };
4356/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004357void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004358 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004359 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004360 // Collect information from the property implementation decl(s).
4361 bool Dynamic = false;
4362 ObjCPropertyImplDecl *SynthesizePID = 0;
4363
4364 // FIXME: Duplicated code due to poor abstraction.
4365 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004366 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004367 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4368 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004369 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004370 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004371 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004372 if (PID->getPropertyDecl() == PD) {
4373 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4374 Dynamic = true;
4375 } else {
4376 SynthesizePID = PID;
4377 }
4378 }
4379 }
4380 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004381 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004382 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004383 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004384 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004385 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004386 if (PID->getPropertyDecl() == PD) {
4387 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4388 Dynamic = true;
4389 } else {
4390 SynthesizePID = PID;
4391 }
4392 }
Mike Stump11289f42009-09-09 15:08:12 +00004393 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004394 }
4395 }
4396
4397 // FIXME: This is not very efficient.
4398 S = "T";
4399
4400 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004401 // GCC has some special rules regarding encoding of properties which
4402 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004403 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004404 true /* outermost type */,
4405 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004406
4407 if (PD->isReadOnly()) {
4408 S += ",R";
4409 } else {
4410 switch (PD->getSetterKind()) {
4411 case ObjCPropertyDecl::Assign: break;
4412 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004413 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004414 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004415 }
4416 }
4417
4418 // It really isn't clear at all what this means, since properties
4419 // are "dynamic by default".
4420 if (Dynamic)
4421 S += ",D";
4422
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004423 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4424 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004425
Daniel Dunbar4932b362008-08-28 04:38:10 +00004426 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4427 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004428 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004429 }
4430
4431 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4432 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004433 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004434 }
4435
4436 if (SynthesizePID) {
4437 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4438 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004439 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004440 }
4441
4442 // FIXME: OBJCGC: weak & strong
4443}
4444
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004445/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004446/// Another legacy compatibility encoding: 32-bit longs are encoded as
4447/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004448/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4449///
4450void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004451 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004452 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004453 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004454 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004455 else
Jay Foad39c79802011-01-12 09:06:06 +00004456 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004457 PointeeTy = IntTy;
4458 }
4459 }
4460}
4461
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004462void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004463 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004464 // We follow the behavior of gcc, expanding structures which are
4465 // directly pointed to, and expanding embedded structures. Note that
4466 // these rules are sufficient to prevent recursive encoding of the
4467 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004468 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004469 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004470}
4471
David Chisnallb190a2c2010-06-04 01:10:52 +00004472static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4473 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004474 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004475 case BuiltinType::Void: return 'v';
4476 case BuiltinType::Bool: return 'B';
4477 case BuiltinType::Char_U:
4478 case BuiltinType::UChar: return 'C';
4479 case BuiltinType::UShort: return 'S';
4480 case BuiltinType::UInt: return 'I';
4481 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004482 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004483 case BuiltinType::UInt128: return 'T';
4484 case BuiltinType::ULongLong: return 'Q';
4485 case BuiltinType::Char_S:
4486 case BuiltinType::SChar: return 'c';
4487 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004488 case BuiltinType::WChar_S:
4489 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004490 case BuiltinType::Int: return 'i';
4491 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004492 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004493 case BuiltinType::LongLong: return 'q';
4494 case BuiltinType::Int128: return 't';
4495 case BuiltinType::Float: return 'f';
4496 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004497 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004498 }
4499}
4500
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004501static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4502 EnumDecl *Enum = ET->getDecl();
4503
4504 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4505 if (!Enum->isFixed())
4506 return 'i';
4507
4508 // The encoding of a fixed enum type matches its fixed underlying type.
4509 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4510}
4511
Jay Foad39c79802011-01-12 09:06:06 +00004512static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004513 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004514 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004515 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004516 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4517 // The GNU runtime requires more information; bitfields are encoded as b,
4518 // then the offset (in bits) of the first element, then the type of the
4519 // bitfield, then the size in bits. For example, in this structure:
4520 //
4521 // struct
4522 // {
4523 // int integer;
4524 // int flags:2;
4525 // };
4526 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4527 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4528 // information is not especially sensible, but we're stuck with it for
4529 // compatibility with GCC, although providing it breaks anything that
4530 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004531 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004532 const RecordDecl *RD = FD->getParent();
4533 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004534 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004535 if (const EnumType *ET = T->getAs<EnumType>())
4536 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004537 else
Jay Foad39c79802011-01-12 09:06:06 +00004538 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004539 }
Richard Smithcaf33902011-10-10 18:28:20 +00004540 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004541}
4542
Daniel Dunbar07d07852009-10-18 21:17:35 +00004543// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004544void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4545 bool ExpandPointedToStructures,
4546 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004547 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004548 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004549 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004550 bool StructField,
4551 bool EncodeBlockParameters,
4552 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004553 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004554 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004555 return EncodeBitField(this, S, T, FD);
4556 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004557 return;
4558 }
Mike Stump11289f42009-09-09 15:08:12 +00004559
John McCall9dd450b2009-09-21 23:43:11 +00004560 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004561 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004562 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004563 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004564 return;
4565 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004566
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004567 // encoding for pointer or r3eference types.
4568 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004569 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004570 if (PT->isObjCSelType()) {
4571 S += ':';
4572 return;
4573 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004574 PointeeTy = PT->getPointeeType();
4575 }
4576 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4577 PointeeTy = RT->getPointeeType();
4578 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004579 bool isReadOnly = false;
4580 // For historical/compatibility reasons, the read-only qualifier of the
4581 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4582 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004583 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004584 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004585 if (OutermostType && T.isConstQualified()) {
4586 isReadOnly = true;
4587 S += 'r';
4588 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004589 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004590 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004591 while (P->getAs<PointerType>())
4592 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004593 if (P.isConstQualified()) {
4594 isReadOnly = true;
4595 S += 'r';
4596 }
4597 }
4598 if (isReadOnly) {
4599 // Another legacy compatibility encoding. Some ObjC qualifier and type
4600 // combinations need to be rearranged.
4601 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004602 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004603 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004604 }
Mike Stump11289f42009-09-09 15:08:12 +00004605
Anders Carlssond8499822007-10-29 05:01:08 +00004606 if (PointeeTy->isCharType()) {
4607 // char pointer types should be encoded as '*' unless it is a
4608 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004609 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004610 S += '*';
4611 return;
4612 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004613 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004614 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4615 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4616 S += '#';
4617 return;
4618 }
4619 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4620 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4621 S += '@';
4622 return;
4623 }
4624 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004625 }
Anders Carlssond8499822007-10-29 05:01:08 +00004626 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004627 getLegacyIntegralTypeEncoding(PointeeTy);
4628
Mike Stump11289f42009-09-09 15:08:12 +00004629 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004630 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004631 return;
4632 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004633
Chris Lattnere7cabb92009-07-13 00:10:46 +00004634 if (const ArrayType *AT =
4635 // Ignore type qualifiers etc.
4636 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004637 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004638 // Incomplete arrays are encoded as a pointer to the array element.
4639 S += '^';
4640
Mike Stump11289f42009-09-09 15:08:12 +00004641 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004642 false, ExpandStructures, FD);
4643 } else {
4644 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004645
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004646 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4647 if (getTypeSize(CAT->getElementType()) == 0)
4648 S += '0';
4649 else
4650 S += llvm::utostr(CAT->getSize().getZExtValue());
4651 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004652 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004653 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4654 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004655 S += '0';
4656 }
Mike Stump11289f42009-09-09 15:08:12 +00004657
4658 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004659 false, ExpandStructures, FD);
4660 S += ']';
4661 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004662 return;
4663 }
Mike Stump11289f42009-09-09 15:08:12 +00004664
John McCall9dd450b2009-09-21 23:43:11 +00004665 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004666 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004667 return;
4668 }
Mike Stump11289f42009-09-09 15:08:12 +00004669
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004670 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004671 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004672 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004673 // Anonymous structures print as '?'
4674 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4675 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004676 if (ClassTemplateSpecializationDecl *Spec
4677 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4678 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4679 std::string TemplateArgsStr
4680 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004681 TemplateArgs.data(),
4682 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004683 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004684
4685 S += TemplateArgsStr;
4686 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004687 } else {
4688 S += '?';
4689 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004690 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004691 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004692 if (!RDecl->isUnion()) {
4693 getObjCEncodingForStructureImpl(RDecl, S, FD);
4694 } else {
4695 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4696 FieldEnd = RDecl->field_end();
4697 Field != FieldEnd; ++Field) {
4698 if (FD) {
4699 S += '"';
4700 S += Field->getNameAsString();
4701 S += '"';
4702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004704 // Special case bit-fields.
4705 if (Field->isBitField()) {
4706 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004707 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004708 } else {
4709 QualType qt = Field->getType();
4710 getLegacyIntegralTypeEncoding(qt);
4711 getObjCEncodingForTypeImpl(qt, S, false, true,
4712 FD, /*OutermostType*/false,
4713 /*EncodingProperty*/false,
4714 /*StructField*/true);
4715 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004716 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004717 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004718 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004719 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004720 return;
4721 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004722
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004723 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004724 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004725 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004726 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004727 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004728 return;
4729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004731 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004732 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004733 if (EncodeBlockParameters) {
4734 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4735
4736 S += '<';
4737 // Block return type
4738 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4739 ExpandPointedToStructures, ExpandStructures,
4740 FD,
4741 false /* OutermostType */,
4742 EncodingProperty,
4743 false /* StructField */,
4744 EncodeBlockParameters,
4745 EncodeClassNames);
4746 // Block self
4747 S += "@?";
4748 // Block parameters
4749 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4750 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4751 E = FPT->arg_type_end(); I && (I != E); ++I) {
4752 getObjCEncodingForTypeImpl(*I, S,
4753 ExpandPointedToStructures,
4754 ExpandStructures,
4755 FD,
4756 false /* OutermostType */,
4757 EncodingProperty,
4758 false /* StructField */,
4759 EncodeBlockParameters,
4760 EncodeClassNames);
4761 }
4762 }
4763 S += '>';
4764 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004765 return;
4766 }
Mike Stump11289f42009-09-09 15:08:12 +00004767
John McCall8b07ec22010-05-15 11:32:37 +00004768 // Ignore protocol qualifiers when mangling at this level.
4769 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4770 T = OT->getBaseType();
4771
John McCall8ccfcb52009-09-24 19:53:00 +00004772 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004773 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004774 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004775 S += '{';
4776 const IdentifierInfo *II = OI->getIdentifier();
4777 S += II->getName();
4778 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004779 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004780 DeepCollectObjCIvars(OI, true, Ivars);
4781 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004782 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004783 if (Field->isBitField())
4784 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004785 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004786 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004787 }
4788 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004789 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004790 }
Mike Stump11289f42009-09-09 15:08:12 +00004791
John McCall9dd450b2009-09-21 23:43:11 +00004792 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004793 if (OPT->isObjCIdType()) {
4794 S += '@';
4795 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004796 }
Mike Stump11289f42009-09-09 15:08:12 +00004797
Steve Narofff0c86112009-10-28 22:03:49 +00004798 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4799 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4800 // Since this is a binary compatibility issue, need to consult with runtime
4801 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004802 S += '#';
4803 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004804 }
Mike Stump11289f42009-09-09 15:08:12 +00004805
Chris Lattnere7cabb92009-07-13 00:10:46 +00004806 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004807 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004808 ExpandPointedToStructures,
4809 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004810 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004811 // Note that we do extended encoding of protocol qualifer list
4812 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004813 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004814 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4815 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004816 S += '<';
4817 S += (*I)->getNameAsString();
4818 S += '>';
4819 }
4820 S += '"';
4821 }
4822 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004823 }
Mike Stump11289f42009-09-09 15:08:12 +00004824
Chris Lattnere7cabb92009-07-13 00:10:46 +00004825 QualType PointeeTy = OPT->getPointeeType();
4826 if (!EncodingProperty &&
4827 isa<TypedefType>(PointeeTy.getTypePtr())) {
4828 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004829 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004830 // {...};
4831 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004832 getObjCEncodingForTypeImpl(PointeeTy, S,
4833 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004834 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004835 return;
4836 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004837
4838 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004839 if (OPT->getInterfaceDecl() &&
4840 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004841 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004842 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004843 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4844 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004845 S += '<';
4846 S += (*I)->getNameAsString();
4847 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004848 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004849 S += '"';
4850 }
4851 return;
4852 }
Mike Stump11289f42009-09-09 15:08:12 +00004853
John McCalla9e6e8d2010-05-17 23:56:34 +00004854 // gcc just blithely ignores member pointers.
4855 // TODO: maybe there should be a mangling for these
4856 if (T->getAs<MemberPointerType>())
4857 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004858
4859 if (T->isVectorType()) {
4860 // This matches gcc's encoding, even though technically it is
4861 // insufficient.
4862 // FIXME. We should do a better job than gcc.
4863 return;
4864 }
4865
David Blaikie83d382b2011-09-23 05:06:16 +00004866 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004867}
4868
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004869void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4870 std::string &S,
4871 const FieldDecl *FD,
4872 bool includeVBases) const {
4873 assert(RDecl && "Expected non-null RecordDecl");
4874 assert(!RDecl->isUnion() && "Should not be called for unions");
4875 if (!RDecl->getDefinition())
4876 return;
4877
4878 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4879 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4880 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4881
4882 if (CXXRec) {
4883 for (CXXRecordDecl::base_class_iterator
4884 BI = CXXRec->bases_begin(),
4885 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4886 if (!BI->isVirtual()) {
4887 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004888 if (base->isEmpty())
4889 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004890 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004891 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4892 std::make_pair(offs, base));
4893 }
4894 }
4895 }
4896
4897 unsigned i = 0;
4898 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4899 FieldEnd = RDecl->field_end();
4900 Field != FieldEnd; ++Field, ++i) {
4901 uint64_t offs = layout.getFieldOffset(i);
4902 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004903 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004904 }
4905
4906 if (CXXRec && includeVBases) {
4907 for (CXXRecordDecl::base_class_iterator
4908 BI = CXXRec->vbases_begin(),
4909 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4910 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004911 if (base->isEmpty())
4912 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004913 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004914 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4915 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4916 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004917 }
4918 }
4919
4920 CharUnits size;
4921 if (CXXRec) {
4922 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4923 } else {
4924 size = layout.getSize();
4925 }
4926
4927 uint64_t CurOffs = 0;
4928 std::multimap<uint64_t, NamedDecl *>::iterator
4929 CurLayObj = FieldOrBaseOffsets.begin();
4930
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004931 if (CXXRec && CXXRec->isDynamicClass() &&
4932 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004933 if (FD) {
4934 S += "\"_vptr$";
4935 std::string recname = CXXRec->getNameAsString();
4936 if (recname.empty()) recname = "?";
4937 S += recname;
4938 S += '"';
4939 }
4940 S += "^^?";
4941 CurOffs += getTypeSize(VoidPtrTy);
4942 }
4943
4944 if (!RDecl->hasFlexibleArrayMember()) {
4945 // Mark the end of the structure.
4946 uint64_t offs = toBits(size);
4947 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4948 std::make_pair(offs, (NamedDecl*)0));
4949 }
4950
4951 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4952 assert(CurOffs <= CurLayObj->first);
4953
4954 if (CurOffs < CurLayObj->first) {
4955 uint64_t padding = CurLayObj->first - CurOffs;
4956 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4957 // packing/alignment of members is different that normal, in which case
4958 // the encoding will be out-of-sync with the real layout.
4959 // If the runtime switches to just consider the size of types without
4960 // taking into account alignment, we could make padding explicit in the
4961 // encoding (e.g. using arrays of chars). The encoding strings would be
4962 // longer then though.
4963 CurOffs += padding;
4964 }
4965
4966 NamedDecl *dcl = CurLayObj->second;
4967 if (dcl == 0)
4968 break; // reached end of structure.
4969
4970 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4971 // We expand the bases without their virtual bases since those are going
4972 // in the initial structure. Note that this differs from gcc which
4973 // expands virtual bases each time one is encountered in the hierarchy,
4974 // making the encoding type bigger than it really is.
4975 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004976 assert(!base->isEmpty());
4977 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004978 } else {
4979 FieldDecl *field = cast<FieldDecl>(dcl);
4980 if (FD) {
4981 S += '"';
4982 S += field->getNameAsString();
4983 S += '"';
4984 }
4985
4986 if (field->isBitField()) {
4987 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004988 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004989 } else {
4990 QualType qt = field->getType();
4991 getLegacyIntegralTypeEncoding(qt);
4992 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4993 /*OutermostType*/false,
4994 /*EncodingProperty*/false,
4995 /*StructField*/true);
4996 CurOffs += getTypeSize(field->getType());
4997 }
4998 }
4999 }
5000}
5001
Mike Stump11289f42009-09-09 15:08:12 +00005002void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005003 std::string& S) const {
5004 if (QT & Decl::OBJC_TQ_In)
5005 S += 'n';
5006 if (QT & Decl::OBJC_TQ_Inout)
5007 S += 'N';
5008 if (QT & Decl::OBJC_TQ_Out)
5009 S += 'o';
5010 if (QT & Decl::OBJC_TQ_Bycopy)
5011 S += 'O';
5012 if (QT & Decl::OBJC_TQ_Byref)
5013 S += 'R';
5014 if (QT & Decl::OBJC_TQ_Oneway)
5015 S += 'V';
5016}
5017
Douglas Gregor3ea72692011-08-12 05:46:01 +00005018TypedefDecl *ASTContext::getObjCIdDecl() const {
5019 if (!ObjCIdDecl) {
5020 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5021 T = getObjCObjectPointerType(T);
5022 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5023 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5024 getTranslationUnitDecl(),
5025 SourceLocation(), SourceLocation(),
5026 &Idents.get("id"), IdInfo);
5027 }
5028
5029 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005030}
5031
Douglas Gregor52e02802011-08-12 06:17:30 +00005032TypedefDecl *ASTContext::getObjCSelDecl() const {
5033 if (!ObjCSelDecl) {
5034 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5035 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5036 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5037 getTranslationUnitDecl(),
5038 SourceLocation(), SourceLocation(),
5039 &Idents.get("SEL"), SelInfo);
5040 }
5041 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005042}
5043
Douglas Gregor0a586182011-08-12 05:59:41 +00005044TypedefDecl *ASTContext::getObjCClassDecl() const {
5045 if (!ObjCClassDecl) {
5046 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5047 T = getObjCObjectPointerType(T);
5048 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5049 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5050 getTranslationUnitDecl(),
5051 SourceLocation(), SourceLocation(),
5052 &Idents.get("Class"), ClassInfo);
5053 }
5054
5055 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005056}
5057
Douglas Gregord53ae832012-01-17 18:09:05 +00005058ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5059 if (!ObjCProtocolClassDecl) {
5060 ObjCProtocolClassDecl
5061 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5062 SourceLocation(),
5063 &Idents.get("Protocol"),
5064 /*PrevDecl=*/0,
5065 SourceLocation(), true);
5066 }
5067
5068 return ObjCProtocolClassDecl;
5069}
5070
Meador Inge5d3fb222012-06-16 03:34:49 +00005071//===----------------------------------------------------------------------===//
5072// __builtin_va_list Construction Functions
5073//===----------------------------------------------------------------------===//
5074
5075static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5076 // typedef char* __builtin_va_list;
5077 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5078 TypeSourceInfo *TInfo
5079 = Context->getTrivialTypeSourceInfo(CharPtrType);
5080
5081 TypedefDecl *VaListTypeDecl
5082 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5083 Context->getTranslationUnitDecl(),
5084 SourceLocation(), SourceLocation(),
5085 &Context->Idents.get("__builtin_va_list"),
5086 TInfo);
5087 return VaListTypeDecl;
5088}
5089
5090static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5091 // typedef void* __builtin_va_list;
5092 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5093 TypeSourceInfo *TInfo
5094 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5095
5096 TypedefDecl *VaListTypeDecl
5097 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5098 Context->getTranslationUnitDecl(),
5099 SourceLocation(), SourceLocation(),
5100 &Context->Idents.get("__builtin_va_list"),
5101 TInfo);
5102 return VaListTypeDecl;
5103}
5104
5105static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5106 // typedef struct __va_list_tag {
5107 RecordDecl *VaListTagDecl;
5108
5109 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5110 Context->getTranslationUnitDecl(),
5111 &Context->Idents.get("__va_list_tag"));
5112 VaListTagDecl->startDefinition();
5113
5114 const size_t NumFields = 5;
5115 QualType FieldTypes[NumFields];
5116 const char *FieldNames[NumFields];
5117
5118 // unsigned char gpr;
5119 FieldTypes[0] = Context->UnsignedCharTy;
5120 FieldNames[0] = "gpr";
5121
5122 // unsigned char fpr;
5123 FieldTypes[1] = Context->UnsignedCharTy;
5124 FieldNames[1] = "fpr";
5125
5126 // unsigned short reserved;
5127 FieldTypes[2] = Context->UnsignedShortTy;
5128 FieldNames[2] = "reserved";
5129
5130 // void* overflow_arg_area;
5131 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5132 FieldNames[3] = "overflow_arg_area";
5133
5134 // void* reg_save_area;
5135 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5136 FieldNames[4] = "reg_save_area";
5137
5138 // Create fields
5139 for (unsigned i = 0; i < NumFields; ++i) {
5140 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5141 SourceLocation(),
5142 SourceLocation(),
5143 &Context->Idents.get(FieldNames[i]),
5144 FieldTypes[i], /*TInfo=*/0,
5145 /*BitWidth=*/0,
5146 /*Mutable=*/false,
5147 ICIS_NoInit);
5148 Field->setAccess(AS_public);
5149 VaListTagDecl->addDecl(Field);
5150 }
5151 VaListTagDecl->completeDefinition();
5152 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005153 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005154
5155 // } __va_list_tag;
5156 TypedefDecl *VaListTagTypedefDecl
5157 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5158 Context->getTranslationUnitDecl(),
5159 SourceLocation(), SourceLocation(),
5160 &Context->Idents.get("__va_list_tag"),
5161 Context->getTrivialTypeSourceInfo(VaListTagType));
5162 QualType VaListTagTypedefType =
5163 Context->getTypedefType(VaListTagTypedefDecl);
5164
5165 // typedef __va_list_tag __builtin_va_list[1];
5166 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5167 QualType VaListTagArrayType
5168 = Context->getConstantArrayType(VaListTagTypedefType,
5169 Size, ArrayType::Normal, 0);
5170 TypeSourceInfo *TInfo
5171 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5172 TypedefDecl *VaListTypedefDecl
5173 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5174 Context->getTranslationUnitDecl(),
5175 SourceLocation(), SourceLocation(),
5176 &Context->Idents.get("__builtin_va_list"),
5177 TInfo);
5178
5179 return VaListTypedefDecl;
5180}
5181
5182static TypedefDecl *
5183CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5184 // typedef struct __va_list_tag {
5185 RecordDecl *VaListTagDecl;
5186 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5187 Context->getTranslationUnitDecl(),
5188 &Context->Idents.get("__va_list_tag"));
5189 VaListTagDecl->startDefinition();
5190
5191 const size_t NumFields = 4;
5192 QualType FieldTypes[NumFields];
5193 const char *FieldNames[NumFields];
5194
5195 // unsigned gp_offset;
5196 FieldTypes[0] = Context->UnsignedIntTy;
5197 FieldNames[0] = "gp_offset";
5198
5199 // unsigned fp_offset;
5200 FieldTypes[1] = Context->UnsignedIntTy;
5201 FieldNames[1] = "fp_offset";
5202
5203 // void* overflow_arg_area;
5204 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5205 FieldNames[2] = "overflow_arg_area";
5206
5207 // void* reg_save_area;
5208 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5209 FieldNames[3] = "reg_save_area";
5210
5211 // Create fields
5212 for (unsigned i = 0; i < NumFields; ++i) {
5213 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5214 VaListTagDecl,
5215 SourceLocation(),
5216 SourceLocation(),
5217 &Context->Idents.get(FieldNames[i]),
5218 FieldTypes[i], /*TInfo=*/0,
5219 /*BitWidth=*/0,
5220 /*Mutable=*/false,
5221 ICIS_NoInit);
5222 Field->setAccess(AS_public);
5223 VaListTagDecl->addDecl(Field);
5224 }
5225 VaListTagDecl->completeDefinition();
5226 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005227 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005228
5229 // } __va_list_tag;
5230 TypedefDecl *VaListTagTypedefDecl
5231 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5232 Context->getTranslationUnitDecl(),
5233 SourceLocation(), SourceLocation(),
5234 &Context->Idents.get("__va_list_tag"),
5235 Context->getTrivialTypeSourceInfo(VaListTagType));
5236 QualType VaListTagTypedefType =
5237 Context->getTypedefType(VaListTagTypedefDecl);
5238
5239 // typedef __va_list_tag __builtin_va_list[1];
5240 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5241 QualType VaListTagArrayType
5242 = Context->getConstantArrayType(VaListTagTypedefType,
5243 Size, ArrayType::Normal,0);
5244 TypeSourceInfo *TInfo
5245 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5246 TypedefDecl *VaListTypedefDecl
5247 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5248 Context->getTranslationUnitDecl(),
5249 SourceLocation(), SourceLocation(),
5250 &Context->Idents.get("__builtin_va_list"),
5251 TInfo);
5252
5253 return VaListTypedefDecl;
5254}
5255
5256static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5257 // typedef int __builtin_va_list[4];
5258 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5259 QualType IntArrayType
5260 = Context->getConstantArrayType(Context->IntTy,
5261 Size, ArrayType::Normal, 0);
5262 TypedefDecl *VaListTypedefDecl
5263 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5264 Context->getTranslationUnitDecl(),
5265 SourceLocation(), SourceLocation(),
5266 &Context->Idents.get("__builtin_va_list"),
5267 Context->getTrivialTypeSourceInfo(IntArrayType));
5268
5269 return VaListTypedefDecl;
5270}
5271
5272static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5273 TargetInfo::BuiltinVaListKind Kind) {
5274 switch (Kind) {
5275 case TargetInfo::CharPtrBuiltinVaList:
5276 return CreateCharPtrBuiltinVaListDecl(Context);
5277 case TargetInfo::VoidPtrBuiltinVaList:
5278 return CreateVoidPtrBuiltinVaListDecl(Context);
5279 case TargetInfo::PowerABIBuiltinVaList:
5280 return CreatePowerABIBuiltinVaListDecl(Context);
5281 case TargetInfo::X86_64ABIBuiltinVaList:
5282 return CreateX86_64ABIBuiltinVaListDecl(Context);
5283 case TargetInfo::PNaClABIBuiltinVaList:
5284 return CreatePNaClABIBuiltinVaListDecl(Context);
5285 }
5286
5287 llvm_unreachable("Unhandled __builtin_va_list type kind");
5288}
5289
5290TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5291 if (!BuiltinVaListDecl)
5292 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5293
5294 return BuiltinVaListDecl;
5295}
5296
Meador Ingecfb60902012-07-01 15:57:25 +00005297QualType ASTContext::getVaListTagType() const {
5298 // Force the creation of VaListTagTy by building the __builtin_va_list
5299 // declaration.
5300 if (VaListTagTy.isNull())
5301 (void) getBuiltinVaListDecl();
5302
5303 return VaListTagTy;
5304}
5305
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005306void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005307 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005308 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005309
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005310 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005311}
5312
John McCalld28ae272009-12-02 08:04:21 +00005313/// \brief Retrieve the template name that corresponds to a non-empty
5314/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005315TemplateName
5316ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5317 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005318 unsigned size = End - Begin;
5319 assert(size > 1 && "set is not overloaded!");
5320
5321 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5322 size * sizeof(FunctionTemplateDecl*));
5323 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5324
5325 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005326 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005327 NamedDecl *D = *I;
5328 assert(isa<FunctionTemplateDecl>(D) ||
5329 (isa<UsingShadowDecl>(D) &&
5330 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5331 *Storage++ = D;
5332 }
5333
5334 return TemplateName(OT);
5335}
5336
Douglas Gregordc572a32009-03-30 22:58:21 +00005337/// \brief Retrieve the template name that represents a qualified
5338/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005339TemplateName
5340ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5341 bool TemplateKeyword,
5342 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005343 assert(NNS && "Missing nested-name-specifier in qualified template name");
5344
Douglas Gregorc42075a2010-02-04 18:10:26 +00005345 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005346 llvm::FoldingSetNodeID ID;
5347 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5348
5349 void *InsertPos = 0;
5350 QualifiedTemplateName *QTN =
5351 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5352 if (!QTN) {
5353 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5354 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5355 }
5356
5357 return TemplateName(QTN);
5358}
5359
5360/// \brief Retrieve the template name that represents a dependent
5361/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005362TemplateName
5363ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5364 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005365 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005366 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005367
5368 llvm::FoldingSetNodeID ID;
5369 DependentTemplateName::Profile(ID, NNS, Name);
5370
5371 void *InsertPos = 0;
5372 DependentTemplateName *QTN =
5373 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5374
5375 if (QTN)
5376 return TemplateName(QTN);
5377
5378 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5379 if (CanonNNS == NNS) {
5380 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5381 } else {
5382 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5383 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005384 DependentTemplateName *CheckQTN =
5385 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5386 assert(!CheckQTN && "Dependent type name canonicalization broken");
5387 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005388 }
5389
5390 DependentTemplateNames.InsertNode(QTN, InsertPos);
5391 return TemplateName(QTN);
5392}
5393
Douglas Gregor71395fa2009-11-04 00:56:37 +00005394/// \brief Retrieve the template name that represents a dependent
5395/// template name such as \c MetaFun::template operator+.
5396TemplateName
5397ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005398 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005399 assert((!NNS || NNS->isDependent()) &&
5400 "Nested name specifier must be dependent");
5401
5402 llvm::FoldingSetNodeID ID;
5403 DependentTemplateName::Profile(ID, NNS, Operator);
5404
5405 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005406 DependentTemplateName *QTN
5407 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005408
5409 if (QTN)
5410 return TemplateName(QTN);
5411
5412 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5413 if (CanonNNS == NNS) {
5414 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5415 } else {
5416 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5417 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005418
5419 DependentTemplateName *CheckQTN
5420 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5421 assert(!CheckQTN && "Dependent template name canonicalization broken");
5422 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005423 }
5424
5425 DependentTemplateNames.InsertNode(QTN, InsertPos);
5426 return TemplateName(QTN);
5427}
5428
Douglas Gregor5590be02011-01-15 06:45:20 +00005429TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005430ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5431 TemplateName replacement) const {
5432 llvm::FoldingSetNodeID ID;
5433 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5434
5435 void *insertPos = 0;
5436 SubstTemplateTemplateParmStorage *subst
5437 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5438
5439 if (!subst) {
5440 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5441 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5442 }
5443
5444 return TemplateName(subst);
5445}
5446
5447TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005448ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5449 const TemplateArgument &ArgPack) const {
5450 ASTContext &Self = const_cast<ASTContext &>(*this);
5451 llvm::FoldingSetNodeID ID;
5452 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5453
5454 void *InsertPos = 0;
5455 SubstTemplateTemplateParmPackStorage *Subst
5456 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5457
5458 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005459 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005460 ArgPack.pack_size(),
5461 ArgPack.pack_begin());
5462 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5463 }
5464
5465 return TemplateName(Subst);
5466}
5467
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005468/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005469/// TargetInfo, produce the corresponding type. The unsigned @p Type
5470/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005471CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005472 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005473 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005474 case TargetInfo::SignedShort: return ShortTy;
5475 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5476 case TargetInfo::SignedInt: return IntTy;
5477 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5478 case TargetInfo::SignedLong: return LongTy;
5479 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5480 case TargetInfo::SignedLongLong: return LongLongTy;
5481 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5482 }
5483
David Blaikie83d382b2011-09-23 05:06:16 +00005484 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005485}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005486
5487//===----------------------------------------------------------------------===//
5488// Type Predicates.
5489//===----------------------------------------------------------------------===//
5490
Fariborz Jahanian96207692009-02-18 21:49:28 +00005491/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5492/// garbage collection attribute.
5493///
John McCall553d45a2011-01-12 00:34:59 +00005494Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005495 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005496 return Qualifiers::GCNone;
5497
David Blaikiebbafb8a2012-03-11 07:00:24 +00005498 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005499 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5500
5501 // Default behaviour under objective-C's gc is for ObjC pointers
5502 // (or pointers to them) be treated as though they were declared
5503 // as __strong.
5504 if (GCAttrs == Qualifiers::GCNone) {
5505 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5506 return Qualifiers::Strong;
5507 else if (Ty->isPointerType())
5508 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5509 } else {
5510 // It's not valid to set GC attributes on anything that isn't a
5511 // pointer.
5512#ifndef NDEBUG
5513 QualType CT = Ty->getCanonicalTypeInternal();
5514 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5515 CT = AT->getElementType();
5516 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5517#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005518 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005519 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005520}
5521
Chris Lattner49af6a42008-04-07 06:51:04 +00005522//===----------------------------------------------------------------------===//
5523// Type Compatibility Testing
5524//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005525
Mike Stump11289f42009-09-09 15:08:12 +00005526/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005527/// compatible.
5528static bool areCompatVectorTypes(const VectorType *LHS,
5529 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005530 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005531 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005532 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005533}
5534
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005535bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5536 QualType SecondVec) {
5537 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5538 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5539
5540 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5541 return true;
5542
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005543 // Treat Neon vector types and most AltiVec vector types as if they are the
5544 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005545 const VectorType *First = FirstVec->getAs<VectorType>();
5546 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005547 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005548 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005549 First->getVectorKind() != VectorType::AltiVecPixel &&
5550 First->getVectorKind() != VectorType::AltiVecBool &&
5551 Second->getVectorKind() != VectorType::AltiVecPixel &&
5552 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005553 return true;
5554
5555 return false;
5556}
5557
Steve Naroff8e6aee52009-07-23 01:01:38 +00005558//===----------------------------------------------------------------------===//
5559// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5560//===----------------------------------------------------------------------===//
5561
5562/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5563/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005564bool
5565ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5566 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005567 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005568 return true;
5569 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5570 E = rProto->protocol_end(); PI != E; ++PI)
5571 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5572 return true;
5573 return false;
5574}
5575
Steve Naroff8e6aee52009-07-23 01:01:38 +00005576/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5577/// return true if lhs's protocols conform to rhs's protocol; false
5578/// otherwise.
5579bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5580 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5581 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5582 return false;
5583}
5584
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005585/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5586/// Class<p1, ...>.
5587bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5588 QualType rhs) {
5589 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5590 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5591 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5592
5593 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5594 E = lhsQID->qual_end(); I != E; ++I) {
5595 bool match = false;
5596 ObjCProtocolDecl *lhsProto = *I;
5597 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5598 E = rhsOPT->qual_end(); J != E; ++J) {
5599 ObjCProtocolDecl *rhsProto = *J;
5600 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5601 match = true;
5602 break;
5603 }
5604 }
5605 if (!match)
5606 return false;
5607 }
5608 return true;
5609}
5610
Steve Naroff8e6aee52009-07-23 01:01:38 +00005611/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5612/// ObjCQualifiedIDType.
5613bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5614 bool compare) {
5615 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005616 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005617 lhs->isObjCIdType() || lhs->isObjCClassType())
5618 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005619 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005620 rhs->isObjCIdType() || rhs->isObjCClassType())
5621 return true;
5622
5623 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005624 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005625
Steve Naroff8e6aee52009-07-23 01:01:38 +00005626 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005627
Steve Naroff8e6aee52009-07-23 01:01:38 +00005628 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005629 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005630 // make sure we check the class hierarchy.
5631 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5632 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5633 E = lhsQID->qual_end(); I != E; ++I) {
5634 // when comparing an id<P> on lhs with a static type on rhs,
5635 // see if static class implements all of id's protocols, directly or
5636 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005637 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005638 return false;
5639 }
5640 }
5641 // If there are no qualifiers and no interface, we have an 'id'.
5642 return true;
5643 }
Mike Stump11289f42009-09-09 15:08:12 +00005644 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005645 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5646 E = lhsQID->qual_end(); I != E; ++I) {
5647 ObjCProtocolDecl *lhsProto = *I;
5648 bool match = false;
5649
5650 // when comparing an id<P> on lhs with a static type on rhs,
5651 // see if static class implements all of id's protocols, directly or
5652 // through its super class and categories.
5653 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5654 E = rhsOPT->qual_end(); J != E; ++J) {
5655 ObjCProtocolDecl *rhsProto = *J;
5656 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5657 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5658 match = true;
5659 break;
5660 }
5661 }
Mike Stump11289f42009-09-09 15:08:12 +00005662 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005663 // make sure we check the class hierarchy.
5664 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5665 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5666 E = lhsQID->qual_end(); I != E; ++I) {
5667 // when comparing an id<P> on lhs with a static type on rhs,
5668 // see if static class implements all of id's protocols, directly or
5669 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005670 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005671 match = true;
5672 break;
5673 }
5674 }
5675 }
5676 if (!match)
5677 return false;
5678 }
Mike Stump11289f42009-09-09 15:08:12 +00005679
Steve Naroff8e6aee52009-07-23 01:01:38 +00005680 return true;
5681 }
Mike Stump11289f42009-09-09 15:08:12 +00005682
Steve Naroff8e6aee52009-07-23 01:01:38 +00005683 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5684 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5685
Mike Stump11289f42009-09-09 15:08:12 +00005686 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005687 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005688 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005689 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5690 E = lhsOPT->qual_end(); I != E; ++I) {
5691 ObjCProtocolDecl *lhsProto = *I;
5692 bool match = false;
5693
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005694 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005695 // see if static class implements all of id's protocols, directly or
5696 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005697 // First, lhs protocols in the qualifier list must be found, direct
5698 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005699 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5700 E = rhsQID->qual_end(); J != E; ++J) {
5701 ObjCProtocolDecl *rhsProto = *J;
5702 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5703 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5704 match = true;
5705 break;
5706 }
5707 }
5708 if (!match)
5709 return false;
5710 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005711
5712 // Static class's protocols, or its super class or category protocols
5713 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5714 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5715 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5716 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5717 // This is rather dubious but matches gcc's behavior. If lhs has
5718 // no type qualifier and its class has no static protocol(s)
5719 // assume that it is mismatch.
5720 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5721 return false;
5722 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5723 LHSInheritedProtocols.begin(),
5724 E = LHSInheritedProtocols.end(); I != E; ++I) {
5725 bool match = false;
5726 ObjCProtocolDecl *lhsProto = (*I);
5727 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5728 E = rhsQID->qual_end(); J != E; ++J) {
5729 ObjCProtocolDecl *rhsProto = *J;
5730 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5731 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5732 match = true;
5733 break;
5734 }
5735 }
5736 if (!match)
5737 return false;
5738 }
5739 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005740 return true;
5741 }
5742 return false;
5743}
5744
Eli Friedman47f77112008-08-22 00:56:42 +00005745/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005746/// compatible for assignment from RHS to LHS. This handles validation of any
5747/// protocol qualifiers on the LHS or RHS.
5748///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005749bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5750 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005751 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5752 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5753
Steve Naroff1329fa02009-07-15 18:40:39 +00005754 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005755 if (LHS->isObjCUnqualifiedIdOrClass() ||
5756 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005757 return true;
5758
John McCall8b07ec22010-05-15 11:32:37 +00005759 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005760 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5761 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005762 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005763
5764 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5765 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5766 QualType(RHSOPT,0));
5767
John McCall8b07ec22010-05-15 11:32:37 +00005768 // If we have 2 user-defined types, fall into that path.
5769 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005770 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005771
Steve Naroff8e6aee52009-07-23 01:01:38 +00005772 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005773}
5774
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005775/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005776/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005777/// arguments in block literals. When passed as arguments, passing 'A*' where
5778/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5779/// not OK. For the return type, the opposite is not OK.
5780bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5781 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005782 const ObjCObjectPointerType *RHSOPT,
5783 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005784 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005785 return true;
5786
5787 if (LHSOPT->isObjCBuiltinType()) {
5788 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5789 }
5790
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005791 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005792 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5793 QualType(RHSOPT,0),
5794 false);
5795
5796 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5797 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5798 if (LHS && RHS) { // We have 2 user-defined types.
5799 if (LHS != RHS) {
5800 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005801 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005802 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005803 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005804 }
5805 else
5806 return true;
5807 }
5808 return false;
5809}
5810
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005811/// getIntersectionOfProtocols - This routine finds the intersection of set
5812/// of protocols inherited from two distinct objective-c pointer objects.
5813/// It is used to build composite qualifier list of the composite type of
5814/// the conditional expression involving two objective-c pointer objects.
5815static
5816void getIntersectionOfProtocols(ASTContext &Context,
5817 const ObjCObjectPointerType *LHSOPT,
5818 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005819 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005820
John McCall8b07ec22010-05-15 11:32:37 +00005821 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5822 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5823 assert(LHS->getInterface() && "LHS must have an interface base");
5824 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005825
5826 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5827 unsigned LHSNumProtocols = LHS->getNumProtocols();
5828 if (LHSNumProtocols > 0)
5829 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5830 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005831 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005832 Context.CollectInheritedProtocols(LHS->getInterface(),
5833 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005834 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5835 LHSInheritedProtocols.end());
5836 }
5837
5838 unsigned RHSNumProtocols = RHS->getNumProtocols();
5839 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005840 ObjCProtocolDecl **RHSProtocols =
5841 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005842 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5843 if (InheritedProtocolSet.count(RHSProtocols[i]))
5844 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005845 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005846 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005847 Context.CollectInheritedProtocols(RHS->getInterface(),
5848 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005849 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5850 RHSInheritedProtocols.begin(),
5851 E = RHSInheritedProtocols.end(); I != E; ++I)
5852 if (InheritedProtocolSet.count((*I)))
5853 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005854 }
5855}
5856
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005857/// areCommonBaseCompatible - Returns common base class of the two classes if
5858/// one found. Note that this is O'2 algorithm. But it will be called as the
5859/// last type comparison in a ?-exp of ObjC pointer types before a
5860/// warning is issued. So, its invokation is extremely rare.
5861QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005862 const ObjCObjectPointerType *Lptr,
5863 const ObjCObjectPointerType *Rptr) {
5864 const ObjCObjectType *LHS = Lptr->getObjectType();
5865 const ObjCObjectType *RHS = Rptr->getObjectType();
5866 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5867 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005868 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005869 return QualType();
5870
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005871 do {
John McCall8b07ec22010-05-15 11:32:37 +00005872 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005873 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005874 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005875 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5876
5877 QualType Result = QualType(LHS, 0);
5878 if (!Protocols.empty())
5879 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5880 Result = getObjCObjectPointerType(Result);
5881 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005882 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005883 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005884
5885 return QualType();
5886}
5887
John McCall8b07ec22010-05-15 11:32:37 +00005888bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5889 const ObjCObjectType *RHS) {
5890 assert(LHS->getInterface() && "LHS is not an interface type");
5891 assert(RHS->getInterface() && "RHS is not an interface type");
5892
Chris Lattner49af6a42008-04-07 06:51:04 +00005893 // Verify that the base decls are compatible: the RHS must be a subclass of
5894 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005895 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005896 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005897
Chris Lattner49af6a42008-04-07 06:51:04 +00005898 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5899 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005900 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005901 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005902
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005903 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5904 // more detailed analysis is required.
5905 if (RHS->getNumProtocols() == 0) {
5906 // OK, if LHS is a superclass of RHS *and*
5907 // this superclass is assignment compatible with LHS.
5908 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005909 bool IsSuperClass =
5910 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5911 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005912 // OK if conversion of LHS to SuperClass results in narrowing of types
5913 // ; i.e., SuperClass may implement at least one of the protocols
5914 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5915 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5916 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005917 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005918 // If super class has no protocols, it is not a match.
5919 if (SuperClassInheritedProtocols.empty())
5920 return false;
5921
5922 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5923 LHSPE = LHS->qual_end();
5924 LHSPI != LHSPE; LHSPI++) {
5925 bool SuperImplementsProtocol = false;
5926 ObjCProtocolDecl *LHSProto = (*LHSPI);
5927
5928 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5929 SuperClassInheritedProtocols.begin(),
5930 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5931 ObjCProtocolDecl *SuperClassProto = (*I);
5932 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5933 SuperImplementsProtocol = true;
5934 break;
5935 }
5936 }
5937 if (!SuperImplementsProtocol)
5938 return false;
5939 }
5940 return true;
5941 }
5942 return false;
5943 }
Mike Stump11289f42009-09-09 15:08:12 +00005944
John McCall8b07ec22010-05-15 11:32:37 +00005945 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5946 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005947 LHSPI != LHSPE; LHSPI++) {
5948 bool RHSImplementsProtocol = false;
5949
5950 // If the RHS doesn't implement the protocol on the left, the types
5951 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005952 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5953 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005954 RHSPI != RHSPE; RHSPI++) {
5955 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005956 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005957 break;
5958 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005959 }
5960 // FIXME: For better diagnostics, consider passing back the protocol name.
5961 if (!RHSImplementsProtocol)
5962 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005963 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005964 // The RHS implements all protocols listed on the LHS.
5965 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005966}
5967
Steve Naroffb7605152009-02-12 17:52:19 +00005968bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5969 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005970 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5971 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005972
Steve Naroff7cae42b2009-07-10 23:34:53 +00005973 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005974 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005975
5976 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5977 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005978}
5979
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005980bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5981 return canAssignObjCInterfaces(
5982 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5983 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5984}
5985
Mike Stump11289f42009-09-09 15:08:12 +00005986/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005987/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005988/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005989/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005990bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5991 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005992 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005993 return hasSameType(LHS, RHS);
5994
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005995 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005996}
5997
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005998bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005999 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006000}
6001
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006002bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6003 return !mergeTypes(LHS, RHS, true).isNull();
6004}
6005
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006006/// mergeTransparentUnionType - if T is a transparent union type and a member
6007/// of T is compatible with SubType, return the merged type, else return
6008/// QualType()
6009QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6010 bool OfBlockPointer,
6011 bool Unqualified) {
6012 if (const RecordType *UT = T->getAsUnionType()) {
6013 RecordDecl *UD = UT->getDecl();
6014 if (UD->hasAttr<TransparentUnionAttr>()) {
6015 for (RecordDecl::field_iterator it = UD->field_begin(),
6016 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006017 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006018 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6019 if (!MT.isNull())
6020 return MT;
6021 }
6022 }
6023 }
6024
6025 return QualType();
6026}
6027
6028/// mergeFunctionArgumentTypes - merge two types which appear as function
6029/// argument types
6030QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6031 bool OfBlockPointer,
6032 bool Unqualified) {
6033 // GNU extension: two types are compatible if they appear as a function
6034 // argument, one of the types is a transparent union type and the other
6035 // type is compatible with a union member
6036 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6037 Unqualified);
6038 if (!lmerge.isNull())
6039 return lmerge;
6040
6041 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6042 Unqualified);
6043 if (!rmerge.isNull())
6044 return rmerge;
6045
6046 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6047}
6048
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006049QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006050 bool OfBlockPointer,
6051 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006052 const FunctionType *lbase = lhs->getAs<FunctionType>();
6053 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006054 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6055 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006056 bool allLTypes = true;
6057 bool allRTypes = true;
6058
6059 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006060 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006061 if (OfBlockPointer) {
6062 QualType RHS = rbase->getResultType();
6063 QualType LHS = lbase->getResultType();
6064 bool UnqualifiedResult = Unqualified;
6065 if (!UnqualifiedResult)
6066 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006067 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006068 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006069 else
John McCall8c6b56f2010-12-15 01:06:38 +00006070 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6071 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006072 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006073
6074 if (Unqualified)
6075 retType = retType.getUnqualifiedType();
6076
6077 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6078 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6079 if (Unqualified) {
6080 LRetType = LRetType.getUnqualifiedType();
6081 RRetType = RRetType.getUnqualifiedType();
6082 }
6083
6084 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006085 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006086 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006087 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006088
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006089 // FIXME: double check this
6090 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6091 // rbase->getRegParmAttr() != 0 &&
6092 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006093 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6094 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006095
Douglas Gregor8c940862010-01-18 17:14:39 +00006096 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006097 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006098 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006099
John McCall8c6b56f2010-12-15 01:06:38 +00006100 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006101 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6102 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006103 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6104 return QualType();
6105
John McCall31168b02011-06-15 23:02:42 +00006106 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6107 return QualType();
6108
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006109 // functypes which return are preferred over those that do not.
6110 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6111 allLTypes = false;
6112 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6113 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006114 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6115 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006116
John McCall31168b02011-06-15 23:02:42 +00006117 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006118
Eli Friedman47f77112008-08-22 00:56:42 +00006119 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006120 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6121 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006122 unsigned lproto_nargs = lproto->getNumArgs();
6123 unsigned rproto_nargs = rproto->getNumArgs();
6124
6125 // Compatible functions must have the same number of arguments
6126 if (lproto_nargs != rproto_nargs)
6127 return QualType();
6128
6129 // Variadic and non-variadic functions aren't compatible
6130 if (lproto->isVariadic() != rproto->isVariadic())
6131 return QualType();
6132
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006133 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6134 return QualType();
6135
Fariborz Jahanian97676972011-09-28 21:52:05 +00006136 if (LangOpts.ObjCAutoRefCount &&
6137 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6138 return QualType();
6139
Eli Friedman47f77112008-08-22 00:56:42 +00006140 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006141 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006142 for (unsigned i = 0; i < lproto_nargs; i++) {
6143 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6144 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006145 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6146 OfBlockPointer,
6147 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006148 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006149
6150 if (Unqualified)
6151 argtype = argtype.getUnqualifiedType();
6152
Eli Friedman47f77112008-08-22 00:56:42 +00006153 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006154 if (Unqualified) {
6155 largtype = largtype.getUnqualifiedType();
6156 rargtype = rargtype.getUnqualifiedType();
6157 }
6158
Chris Lattner465fa322008-10-05 17:34:18 +00006159 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6160 allLTypes = false;
6161 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6162 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006163 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006164
Eli Friedman47f77112008-08-22 00:56:42 +00006165 if (allLTypes) return lhs;
6166 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006167
6168 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6169 EPI.ExtInfo = einfo;
6170 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006171 }
6172
6173 if (lproto) allRTypes = false;
6174 if (rproto) allLTypes = false;
6175
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006176 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006177 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006178 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006179 if (proto->isVariadic()) return QualType();
6180 // Check that the types are compatible with the types that
6181 // would result from default argument promotions (C99 6.7.5.3p15).
6182 // The only types actually affected are promotable integer
6183 // types and floats, which would be passed as a different
6184 // type depending on whether the prototype is visible.
6185 unsigned proto_nargs = proto->getNumArgs();
6186 for (unsigned i = 0; i < proto_nargs; ++i) {
6187 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006188
6189 // Look at the promotion type of enum types, since that is the type used
6190 // to pass enum values.
6191 if (const EnumType *Enum = argTy->getAs<EnumType>())
6192 argTy = Enum->getDecl()->getPromotionType();
6193
Eli Friedman47f77112008-08-22 00:56:42 +00006194 if (argTy->isPromotableIntegerType() ||
6195 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6196 return QualType();
6197 }
6198
6199 if (allLTypes) return lhs;
6200 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006201
6202 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6203 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006204 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006205 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006206 }
6207
6208 if (allLTypes) return lhs;
6209 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006210 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006211}
6212
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006213QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006214 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006215 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006216 // C++ [expr]: If an expression initially has the type "reference to T", the
6217 // type is adjusted to "T" prior to any further analysis, the expression
6218 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006219 // expression is an lvalue unless the reference is an rvalue reference and
6220 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006221 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6222 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006223
6224 if (Unqualified) {
6225 LHS = LHS.getUnqualifiedType();
6226 RHS = RHS.getUnqualifiedType();
6227 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006228
Eli Friedman47f77112008-08-22 00:56:42 +00006229 QualType LHSCan = getCanonicalType(LHS),
6230 RHSCan = getCanonicalType(RHS);
6231
6232 // If two types are identical, they are compatible.
6233 if (LHSCan == RHSCan)
6234 return LHS;
6235
John McCall8ccfcb52009-09-24 19:53:00 +00006236 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006237 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6238 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006239 if (LQuals != RQuals) {
6240 // If any of these qualifiers are different, we have a type
6241 // mismatch.
6242 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006243 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6244 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006245 return QualType();
6246
6247 // Exactly one GC qualifier difference is allowed: __strong is
6248 // okay if the other type has no GC qualifier but is an Objective
6249 // C object pointer (i.e. implicitly strong by default). We fix
6250 // this by pretending that the unqualified type was actually
6251 // qualified __strong.
6252 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6253 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6254 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6255
6256 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6257 return QualType();
6258
6259 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6260 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6261 }
6262 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6263 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6264 }
Eli Friedman47f77112008-08-22 00:56:42 +00006265 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006266 }
6267
6268 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006269
Eli Friedmandcca6332009-06-01 01:22:52 +00006270 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6271 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006272
Chris Lattnerfd652912008-01-14 05:45:46 +00006273 // We want to consider the two function types to be the same for these
6274 // comparisons, just force one to the other.
6275 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6276 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006277
6278 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006279 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6280 LHSClass = Type::ConstantArray;
6281 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6282 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006283
John McCall8b07ec22010-05-15 11:32:37 +00006284 // ObjCInterfaces are just specialized ObjCObjects.
6285 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6286 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6287
Nate Begemance4d7fc2008-04-18 23:10:10 +00006288 // Canonicalize ExtVector -> Vector.
6289 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6290 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006291
Chris Lattner95554662008-04-07 05:43:21 +00006292 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006293 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006294 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006295 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006296 // Compatibility is based on the underlying type, not the promotion
6297 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006298 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006299 QualType TINT = ETy->getDecl()->getIntegerType();
6300 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006301 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006302 }
John McCall9dd450b2009-09-21 23:43:11 +00006303 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006304 QualType TINT = ETy->getDecl()->getIntegerType();
6305 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006306 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006307 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006308 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006309 if (OfBlockPointer && !BlockReturnType) {
6310 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6311 return LHS;
6312 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6313 return RHS;
6314 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006315
Eli Friedman47f77112008-08-22 00:56:42 +00006316 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006317 }
Eli Friedman47f77112008-08-22 00:56:42 +00006318
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006319 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006320 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006321#define TYPE(Class, Base)
6322#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006323#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006324#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6325#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6326#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006327 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006328
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006329 case Type::LValueReference:
6330 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006331 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006332 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006333
John McCall8b07ec22010-05-15 11:32:37 +00006334 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006335 case Type::IncompleteArray:
6336 case Type::VariableArray:
6337 case Type::FunctionProto:
6338 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006339 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006340
Chris Lattnerfd652912008-01-14 05:45:46 +00006341 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006342 {
6343 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006344 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6345 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006346 if (Unqualified) {
6347 LHSPointee = LHSPointee.getUnqualifiedType();
6348 RHSPointee = RHSPointee.getUnqualifiedType();
6349 }
6350 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6351 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006352 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006353 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006354 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006355 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006356 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006357 return getPointerType(ResultType);
6358 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006359 case Type::BlockPointer:
6360 {
6361 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006362 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6363 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006364 if (Unqualified) {
6365 LHSPointee = LHSPointee.getUnqualifiedType();
6366 RHSPointee = RHSPointee.getUnqualifiedType();
6367 }
6368 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6369 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006370 if (ResultType.isNull()) return QualType();
6371 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6372 return LHS;
6373 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6374 return RHS;
6375 return getBlockPointerType(ResultType);
6376 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006377 case Type::Atomic:
6378 {
6379 // Merge two pointer types, while trying to preserve typedef info
6380 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6381 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6382 if (Unqualified) {
6383 LHSValue = LHSValue.getUnqualifiedType();
6384 RHSValue = RHSValue.getUnqualifiedType();
6385 }
6386 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6387 Unqualified);
6388 if (ResultType.isNull()) return QualType();
6389 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6390 return LHS;
6391 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6392 return RHS;
6393 return getAtomicType(ResultType);
6394 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006395 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006396 {
6397 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6398 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6399 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6400 return QualType();
6401
6402 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6403 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006404 if (Unqualified) {
6405 LHSElem = LHSElem.getUnqualifiedType();
6406 RHSElem = RHSElem.getUnqualifiedType();
6407 }
6408
6409 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006410 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006411 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6412 return LHS;
6413 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6414 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006415 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6416 ArrayType::ArraySizeModifier(), 0);
6417 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6418 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006419 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6420 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006421 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6422 return LHS;
6423 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6424 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006425 if (LVAT) {
6426 // FIXME: This isn't correct! But tricky to implement because
6427 // the array's size has to be the size of LHS, but the type
6428 // has to be different.
6429 return LHS;
6430 }
6431 if (RVAT) {
6432 // FIXME: This isn't correct! But tricky to implement because
6433 // the array's size has to be the size of RHS, but the type
6434 // has to be different.
6435 return RHS;
6436 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006437 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6438 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006439 return getIncompleteArrayType(ResultType,
6440 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006441 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006442 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006443 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006444 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006445 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006446 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006447 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006448 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006449 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006450 case Type::Complex:
6451 // Distinct complex types are incompatible.
6452 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006453 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006454 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006455 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6456 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006457 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006458 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006459 case Type::ObjCObject: {
6460 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006461 // FIXME: This should be type compatibility, e.g. whether
6462 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006463 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6464 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6465 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006466 return LHS;
6467
Eli Friedman47f77112008-08-22 00:56:42 +00006468 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006469 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006470 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006471 if (OfBlockPointer) {
6472 if (canAssignObjCInterfacesInBlockPointer(
6473 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006474 RHS->getAs<ObjCObjectPointerType>(),
6475 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006476 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006477 return QualType();
6478 }
John McCall9dd450b2009-09-21 23:43:11 +00006479 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6480 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006481 return LHS;
6482
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006483 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006484 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006485 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006486
David Blaikie8a40f702012-01-17 06:56:22 +00006487 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006488}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006489
Fariborz Jahanian97676972011-09-28 21:52:05 +00006490bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6491 const FunctionProtoType *FromFunctionType,
6492 const FunctionProtoType *ToFunctionType) {
6493 if (FromFunctionType->hasAnyConsumedArgs() !=
6494 ToFunctionType->hasAnyConsumedArgs())
6495 return false;
6496 FunctionProtoType::ExtProtoInfo FromEPI =
6497 FromFunctionType->getExtProtoInfo();
6498 FunctionProtoType::ExtProtoInfo ToEPI =
6499 ToFunctionType->getExtProtoInfo();
6500 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6501 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6502 ArgIdx != NumArgs; ++ArgIdx) {
6503 if (FromEPI.ConsumedArguments[ArgIdx] !=
6504 ToEPI.ConsumedArguments[ArgIdx])
6505 return false;
6506 }
6507 return true;
6508}
6509
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006510/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6511/// 'RHS' attributes and returns the merged version; including for function
6512/// return types.
6513QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6514 QualType LHSCan = getCanonicalType(LHS),
6515 RHSCan = getCanonicalType(RHS);
6516 // If two types are identical, they are compatible.
6517 if (LHSCan == RHSCan)
6518 return LHS;
6519 if (RHSCan->isFunctionType()) {
6520 if (!LHSCan->isFunctionType())
6521 return QualType();
6522 QualType OldReturnType =
6523 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6524 QualType NewReturnType =
6525 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6526 QualType ResReturnType =
6527 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6528 if (ResReturnType.isNull())
6529 return QualType();
6530 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6531 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6532 // In either case, use OldReturnType to build the new function type.
6533 const FunctionType *F = LHS->getAs<FunctionType>();
6534 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006535 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6536 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006537 QualType ResultType
6538 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006539 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006540 return ResultType;
6541 }
6542 }
6543 return QualType();
6544 }
6545
6546 // If the qualifiers are different, the types can still be merged.
6547 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6548 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6549 if (LQuals != RQuals) {
6550 // If any of these qualifiers are different, we have a type mismatch.
6551 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6552 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6553 return QualType();
6554
6555 // Exactly one GC qualifier difference is allowed: __strong is
6556 // okay if the other type has no GC qualifier but is an Objective
6557 // C object pointer (i.e. implicitly strong by default). We fix
6558 // this by pretending that the unqualified type was actually
6559 // qualified __strong.
6560 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6561 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6562 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6563
6564 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6565 return QualType();
6566
6567 if (GC_L == Qualifiers::Strong)
6568 return LHS;
6569 if (GC_R == Qualifiers::Strong)
6570 return RHS;
6571 return QualType();
6572 }
6573
6574 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6575 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6576 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6577 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6578 if (ResQT == LHSBaseQT)
6579 return LHS;
6580 if (ResQT == RHSBaseQT)
6581 return RHS;
6582 }
6583 return QualType();
6584}
6585
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006586//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006587// Integer Predicates
6588//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006589
Jay Foad39c79802011-01-12 09:06:06 +00006590unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006591 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006592 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006593 if (T->isBooleanType())
6594 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006595 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006596 return (unsigned)getTypeSize(T);
6597}
6598
6599QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006600 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006601
6602 // Turn <4 x signed int> -> <4 x unsigned int>
6603 if (const VectorType *VTy = T->getAs<VectorType>())
6604 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006605 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006606
6607 // For enums, we return the unsigned version of the base type.
6608 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006609 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006610
6611 const BuiltinType *BTy = T->getAs<BuiltinType>();
6612 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006613 switch (BTy->getKind()) {
6614 case BuiltinType::Char_S:
6615 case BuiltinType::SChar:
6616 return UnsignedCharTy;
6617 case BuiltinType::Short:
6618 return UnsignedShortTy;
6619 case BuiltinType::Int:
6620 return UnsignedIntTy;
6621 case BuiltinType::Long:
6622 return UnsignedLongTy;
6623 case BuiltinType::LongLong:
6624 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006625 case BuiltinType::Int128:
6626 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006627 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006628 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006629 }
6630}
6631
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006632ASTMutationListener::~ASTMutationListener() { }
6633
Chris Lattnerecd79c62009-06-14 00:45:47 +00006634
6635//===----------------------------------------------------------------------===//
6636// Builtin Type Computation
6637//===----------------------------------------------------------------------===//
6638
6639/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006640/// pointer over the consumed characters. This returns the resultant type. If
6641/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6642/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6643/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006644///
6645/// RequiresICE is filled in on return to indicate whether the value is required
6646/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006647static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006648 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006649 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006650 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006651 // Modifiers.
6652 int HowLong = 0;
6653 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006654 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006655
Chris Lattnerdc226c22010-10-01 22:42:38 +00006656 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006657 bool Done = false;
6658 while (!Done) {
6659 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006660 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006661 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006662 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006663 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006664 case 'S':
6665 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6666 assert(!Signed && "Can't use 'S' modifier multiple times!");
6667 Signed = true;
6668 break;
6669 case 'U':
6670 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6671 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6672 Unsigned = true;
6673 break;
6674 case 'L':
6675 assert(HowLong <= 2 && "Can't have LLLL modifier");
6676 ++HowLong;
6677 break;
6678 }
6679 }
6680
6681 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006682
Chris Lattnerecd79c62009-06-14 00:45:47 +00006683 // Read the base type.
6684 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006685 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006686 case 'v':
6687 assert(HowLong == 0 && !Signed && !Unsigned &&
6688 "Bad modifiers used with 'v'!");
6689 Type = Context.VoidTy;
6690 break;
6691 case 'f':
6692 assert(HowLong == 0 && !Signed && !Unsigned &&
6693 "Bad modifiers used with 'f'!");
6694 Type = Context.FloatTy;
6695 break;
6696 case 'd':
6697 assert(HowLong < 2 && !Signed && !Unsigned &&
6698 "Bad modifiers used with 'd'!");
6699 if (HowLong)
6700 Type = Context.LongDoubleTy;
6701 else
6702 Type = Context.DoubleTy;
6703 break;
6704 case 's':
6705 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6706 if (Unsigned)
6707 Type = Context.UnsignedShortTy;
6708 else
6709 Type = Context.ShortTy;
6710 break;
6711 case 'i':
6712 if (HowLong == 3)
6713 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6714 else if (HowLong == 2)
6715 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6716 else if (HowLong == 1)
6717 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6718 else
6719 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6720 break;
6721 case 'c':
6722 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6723 if (Signed)
6724 Type = Context.SignedCharTy;
6725 else if (Unsigned)
6726 Type = Context.UnsignedCharTy;
6727 else
6728 Type = Context.CharTy;
6729 break;
6730 case 'b': // boolean
6731 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6732 Type = Context.BoolTy;
6733 break;
6734 case 'z': // size_t.
6735 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6736 Type = Context.getSizeType();
6737 break;
6738 case 'F':
6739 Type = Context.getCFConstantStringType();
6740 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006741 case 'G':
6742 Type = Context.getObjCIdType();
6743 break;
6744 case 'H':
6745 Type = Context.getObjCSelType();
6746 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006747 case 'a':
6748 Type = Context.getBuiltinVaListType();
6749 assert(!Type.isNull() && "builtin va list type not initialized!");
6750 break;
6751 case 'A':
6752 // This is a "reference" to a va_list; however, what exactly
6753 // this means depends on how va_list is defined. There are two
6754 // different kinds of va_list: ones passed by value, and ones
6755 // passed by reference. An example of a by-value va_list is
6756 // x86, where va_list is a char*. An example of by-ref va_list
6757 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6758 // we want this argument to be a char*&; for x86-64, we want
6759 // it to be a __va_list_tag*.
6760 Type = Context.getBuiltinVaListType();
6761 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006762 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006763 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006764 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006765 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006766 break;
6767 case 'V': {
6768 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006769 unsigned NumElements = strtoul(Str, &End, 10);
6770 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006771 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006772
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006773 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6774 RequiresICE, false);
6775 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006776
6777 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006778 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006779 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006780 break;
6781 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006782 case 'E': {
6783 char *End;
6784
6785 unsigned NumElements = strtoul(Str, &End, 10);
6786 assert(End != Str && "Missing vector size");
6787
6788 Str = End;
6789
6790 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6791 false);
6792 Type = Context.getExtVectorType(ElementType, NumElements);
6793 break;
6794 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006795 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006796 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6797 false);
6798 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006799 Type = Context.getComplexType(ElementType);
6800 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006801 }
6802 case 'Y' : {
6803 Type = Context.getPointerDiffType();
6804 break;
6805 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006806 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006807 Type = Context.getFILEType();
6808 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006809 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006810 return QualType();
6811 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006812 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006813 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006814 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006815 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006816 else
6817 Type = Context.getjmp_bufType();
6818
Mike Stump2adb4da2009-07-28 23:47:15 +00006819 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006820 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006821 return QualType();
6822 }
6823 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006824 case 'K':
6825 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6826 Type = Context.getucontext_tType();
6827
6828 if (Type.isNull()) {
6829 Error = ASTContext::GE_Missing_ucontext;
6830 return QualType();
6831 }
6832 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006833 }
Mike Stump11289f42009-09-09 15:08:12 +00006834
Chris Lattnerdc226c22010-10-01 22:42:38 +00006835 // If there are modifiers and if we're allowed to parse them, go for it.
6836 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006837 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006838 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006839 default: Done = true; --Str; break;
6840 case '*':
6841 case '&': {
6842 // Both pointers and references can have their pointee types
6843 // qualified with an address space.
6844 char *End;
6845 unsigned AddrSpace = strtoul(Str, &End, 10);
6846 if (End != Str && AddrSpace != 0) {
6847 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6848 Str = End;
6849 }
6850 if (c == '*')
6851 Type = Context.getPointerType(Type);
6852 else
6853 Type = Context.getLValueReferenceType(Type);
6854 break;
6855 }
6856 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6857 case 'C':
6858 Type = Type.withConst();
6859 break;
6860 case 'D':
6861 Type = Context.getVolatileType(Type);
6862 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006863 case 'R':
6864 Type = Type.withRestrict();
6865 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006866 }
6867 }
Chris Lattner84733392010-10-01 07:13:18 +00006868
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006869 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006870 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006871
Chris Lattnerecd79c62009-06-14 00:45:47 +00006872 return Type;
6873}
6874
6875/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006876QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006877 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006878 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006879 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006880
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006881 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006882
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006883 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006884 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006885 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6886 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006887 if (Error != GE_None)
6888 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006889
6890 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6891
Chris Lattnerecd79c62009-06-14 00:45:47 +00006892 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006893 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006894 if (Error != GE_None)
6895 return QualType();
6896
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006897 // If this argument is required to be an IntegerConstantExpression and the
6898 // caller cares, fill in the bitmask we return.
6899 if (RequiresICE && IntegerConstantArgs)
6900 *IntegerConstantArgs |= 1 << ArgTypes.size();
6901
Chris Lattnerecd79c62009-06-14 00:45:47 +00006902 // Do array -> pointer decay. The builtin should use the decayed type.
6903 if (Ty->isArrayType())
6904 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006905
Chris Lattnerecd79c62009-06-14 00:45:47 +00006906 ArgTypes.push_back(Ty);
6907 }
6908
6909 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6910 "'.' should only occur at end of builtin type list!");
6911
John McCall991eb4b2010-12-21 00:44:39 +00006912 FunctionType::ExtInfo EI;
6913 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6914
6915 bool Variadic = (TypeStr[0] == '.');
6916
6917 // We really shouldn't be making a no-proto type here, especially in C++.
6918 if (ArgTypes.empty() && Variadic)
6919 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006920
John McCalldb40c7f2010-12-14 08:05:40 +00006921 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006922 EPI.ExtInfo = EI;
6923 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006924
6925 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006926}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006927
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006928GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6929 GVALinkage External = GVA_StrongExternal;
6930
6931 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006932 switch (L) {
6933 case NoLinkage:
6934 case InternalLinkage:
6935 case UniqueExternalLinkage:
6936 return GVA_Internal;
6937
6938 case ExternalLinkage:
6939 switch (FD->getTemplateSpecializationKind()) {
6940 case TSK_Undeclared:
6941 case TSK_ExplicitSpecialization:
6942 External = GVA_StrongExternal;
6943 break;
6944
6945 case TSK_ExplicitInstantiationDefinition:
6946 return GVA_ExplicitTemplateInstantiation;
6947
6948 case TSK_ExplicitInstantiationDeclaration:
6949 case TSK_ImplicitInstantiation:
6950 External = GVA_TemplateInstantiation;
6951 break;
6952 }
6953 }
6954
6955 if (!FD->isInlined())
6956 return External;
6957
David Blaikiebbafb8a2012-03-11 07:00:24 +00006958 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006959 // GNU or C99 inline semantics. Determine whether this symbol should be
6960 // externally visible.
6961 if (FD->isInlineDefinitionExternallyVisible())
6962 return External;
6963
6964 // C99 inline semantics, where the symbol is not externally visible.
6965 return GVA_C99Inline;
6966 }
6967
6968 // C++0x [temp.explicit]p9:
6969 // [ Note: The intent is that an inline function that is the subject of
6970 // an explicit instantiation declaration will still be implicitly
6971 // instantiated when used so that the body can be considered for
6972 // inlining, but that no out-of-line copy of the inline function would be
6973 // generated in the translation unit. -- end note ]
6974 if (FD->getTemplateSpecializationKind()
6975 == TSK_ExplicitInstantiationDeclaration)
6976 return GVA_C99Inline;
6977
6978 return GVA_CXXInline;
6979}
6980
6981GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6982 // If this is a static data member, compute the kind of template
6983 // specialization. Otherwise, this variable is not part of a
6984 // template.
6985 TemplateSpecializationKind TSK = TSK_Undeclared;
6986 if (VD->isStaticDataMember())
6987 TSK = VD->getTemplateSpecializationKind();
6988
6989 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006990 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006991 VD->getType()->getLinkage() == UniqueExternalLinkage)
6992 L = UniqueExternalLinkage;
6993
6994 switch (L) {
6995 case NoLinkage:
6996 case InternalLinkage:
6997 case UniqueExternalLinkage:
6998 return GVA_Internal;
6999
7000 case ExternalLinkage:
7001 switch (TSK) {
7002 case TSK_Undeclared:
7003 case TSK_ExplicitSpecialization:
7004 return GVA_StrongExternal;
7005
7006 case TSK_ExplicitInstantiationDeclaration:
7007 llvm_unreachable("Variable should not be instantiated");
7008 // Fall through to treat this like any other instantiation.
7009
7010 case TSK_ExplicitInstantiationDefinition:
7011 return GVA_ExplicitTemplateInstantiation;
7012
7013 case TSK_ImplicitInstantiation:
7014 return GVA_TemplateInstantiation;
7015 }
7016 }
7017
David Blaikie8a40f702012-01-17 06:56:22 +00007018 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007019}
7020
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007021bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007022 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7023 if (!VD->isFileVarDecl())
7024 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007025 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007026 return false;
7027
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007028 // Weak references don't produce any output by themselves.
7029 if (D->hasAttr<WeakRefAttr>())
7030 return false;
7031
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007032 // Aliases and used decls are required.
7033 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7034 return true;
7035
7036 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7037 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007038 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007039 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007040
7041 // Constructors and destructors are required.
7042 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7043 return true;
7044
7045 // The key function for a class is required.
7046 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7047 const CXXRecordDecl *RD = MD->getParent();
7048 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7049 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7050 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7051 return true;
7052 }
7053 }
7054
7055 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7056
7057 // static, static inline, always_inline, and extern inline functions can
7058 // always be deferred. Normal inline functions can be deferred in C99/C++.
7059 // Implicit template instantiations can also be deferred in C++.
7060 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007061 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007062 return false;
7063 return true;
7064 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007065
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007066 const VarDecl *VD = cast<VarDecl>(D);
7067 assert(VD->isFileVarDecl() && "Expected file scoped var");
7068
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007069 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7070 return false;
7071
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007072 // Structs that have non-trivial constructors or destructors are required.
7073
7074 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007075 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007076 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7077 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007078 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7079 RD->hasTrivialCopyConstructor() &&
7080 RD->hasTrivialMoveConstructor() &&
7081 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007082 return true;
7083 }
7084 }
7085
7086 GVALinkage L = GetGVALinkageForVariable(VD);
7087 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7088 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7089 return false;
7090 }
7091
7092 return true;
7093}
Charles Davis53c59df2010-08-16 03:33:14 +00007094
Charles Davis99202b32010-11-09 18:04:24 +00007095CallingConv ASTContext::getDefaultMethodCallConv() {
7096 // Pass through to the C++ ABI object
7097 return ABI->getDefaultMethodCallConv();
7098}
7099
Jay Foad39c79802011-01-12 09:06:06 +00007100bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007101 // Pass through to the C++ ABI object
7102 return ABI->isNearlyEmpty(RD);
7103}
7104
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007105MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007106 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007107 case CXXABI_ARM:
7108 case CXXABI_Itanium:
7109 return createItaniumMangleContext(*this, getDiagnostics());
7110 case CXXABI_Microsoft:
7111 return createMicrosoftMangleContext(*this, getDiagnostics());
7112 }
David Blaikie83d382b2011-09-23 05:06:16 +00007113 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007114}
7115
Charles Davis53c59df2010-08-16 03:33:14 +00007116CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007117
7118size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007119 return ASTRecordLayouts.getMemorySize()
7120 + llvm::capacity_in_bytes(ObjCLayouts)
7121 + llvm::capacity_in_bytes(KeyFunctions)
7122 + llvm::capacity_in_bytes(ObjCImpls)
7123 + llvm::capacity_in_bytes(BlockVarCopyInits)
7124 + llvm::capacity_in_bytes(DeclAttrs)
7125 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7126 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7127 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7128 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7129 + llvm::capacity_in_bytes(OverriddenMethods)
7130 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007131 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007132 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007133}
Ted Kremenek540017e2011-10-06 05:00:56 +00007134
Douglas Gregor63798542012-02-20 19:44:39 +00007135unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7136 CXXRecordDecl *Lambda = CallOperator->getParent();
7137 return LambdaMangleContexts[Lambda->getDeclContext()]
7138 .getManglingNumber(CallOperator);
7139}
7140
7141
Ted Kremenek540017e2011-10-06 05:00:56 +00007142void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7143 ParamIndices[D] = index;
7144}
7145
7146unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7147 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7148 assert(I != ParamIndices.end() &&
7149 "ParmIndices lacks entry set by ParmVarDecl");
7150 return I->second;
7151}