blob: c83e70a72bf4da0830e749a2dce7d1a0b6a6ae2f [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoec925312012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000037#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000075 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000076
77 // If there are no comments anywhere, we won't find anything.
78 if (RawComments.empty())
79 return NULL;
80
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000081 // Find declaration location.
82 // For Objective-C declarations we generally don't expect to have multiple
83 // declarators, thus use declaration starting location as the "declaration
84 // location".
85 // For all other declarations multiple declarators are used quite frequently,
86 // so we use the location of the identifier as the "declaration location".
87 SourceLocation DeclLoc;
88 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
89 isa<ObjCPropertyDecl>(D))
90 DeclLoc = D->getLocStart();
91 else
92 DeclLoc = D->getLocation();
93
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000094 // If the declaration doesn't map directly to a location in a file, we
95 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000096 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
97 return NULL;
98
99 // Find the comment that occurs just after this declaration.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000100 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
101 ArrayRef<RawComment *>::iterator Comment
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000102 = std::lower_bound(RawComments.begin(),
103 RawComments.end(),
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 &CommentAtDeclLoc,
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105 BeforeThanCompare<RawComment>(SourceMgr));
106
107 // Decompose the location for the declaration and find the beginning of the
108 // file buffer.
109 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
110
111 // First check whether we have a trailing comment.
112 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000113 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000114 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000116 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // Check that Doxygen trailing comment comes after the declaration, starts
118 // on the same line and in the same file as the declaration.
119 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
120 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
121 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
122 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000123 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 }
125 }
126
127 // The comment just after the declaration was not a trailing comment.
128 // Let's look at the previous comment.
129 if (Comment == RawComments.begin())
130 return NULL;
131 --Comment;
132
133 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000134 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000135 return NULL;
136
137 // Decompose the end of the comment.
138 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000139 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000140
141 // If the comment and the declaration aren't in the same file, then they
142 // aren't related.
143 if (DeclLocDecomp.first != CommentEndDecomp.first)
144 return NULL;
145
146 // Get the corresponding buffer.
147 bool Invalid = false;
148 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
149 &Invalid).data();
150 if (Invalid)
151 return NULL;
152
153 // Extract text between the comment and declaration.
154 StringRef Text(Buffer + CommentEndDecomp.second,
155 DeclLocDecomp.second - CommentEndDecomp.second);
156
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000157 // There should be no other declarations or preprocessor directives between
158 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000159 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000160 return NULL;
161
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000163}
164
165const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
166 // Check whether we have cached a comment string for this declaration
167 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000168 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000170 if (Pos != DeclComments.end()) {
171 RawAndParsedComment C = Pos->second;
172 return C.first;
173 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000174
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000175 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000176 // If we found a comment, it should be a documentation comment.
177 assert(!RC || RC->isDocumentation());
Dmitri Gribenko08630052012-07-06 15:40:08 +0000178 DeclComments[D] =
179 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000180 if (RC)
181 RC->setAttached();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000182 return RC;
183}
184
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000185comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
186 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
187 = DeclComments.find(D);
188 const RawComment *RC;
189 if (Pos != DeclComments.end()) {
190 RawAndParsedComment C = Pos->second;
191 if (comments::FullComment *FC = C.second)
192 return FC;
193 RC = C.first;
194 } else
195 RC = getRawCommentForDecl(D);
196
197 if (!RC)
198 return NULL;
199
200 const StringRef RawText = RC->getRawText(SourceMgr);
201 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
202 RawText.begin(), RawText.end());
203
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000204 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
205 S.setDecl(D);
206 comments::Parser P(L, S, getAllocator(), getSourceManager(),
207 getDiagnostics());
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000208
209 comments::FullComment *FC = P.parseFullComment();
210 DeclComments[D].second = FC;
211 return FC;
212}
213
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000214void
215ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
216 TemplateTemplateParmDecl *Parm) {
217 ID.AddInteger(Parm->getDepth());
218 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000219 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000220
221 TemplateParameterList *Params = Parm->getTemplateParameters();
222 ID.AddInteger(Params->size());
223 for (TemplateParameterList::const_iterator P = Params->begin(),
224 PEnd = Params->end();
225 P != PEnd; ++P) {
226 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
227 ID.AddInteger(0);
228 ID.AddBoolean(TTP->isParameterPack());
229 continue;
230 }
231
232 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
233 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000234 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000235 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000236 if (NTTP->isExpandedParameterPack()) {
237 ID.AddBoolean(true);
238 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000239 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
240 QualType T = NTTP->getExpansionType(I);
241 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
242 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000243 } else
244 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000245 continue;
246 }
247
248 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
249 ID.AddInteger(2);
250 Profile(ID, TTP);
251 }
252}
253
254TemplateTemplateParmDecl *
255ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000256 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000257 // Check if we already have a canonical template template parameter.
258 llvm::FoldingSetNodeID ID;
259 CanonicalTemplateTemplateParm::Profile(ID, TTP);
260 void *InsertPos = 0;
261 CanonicalTemplateTemplateParm *Canonical
262 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
263 if (Canonical)
264 return Canonical->getParam();
265
266 // Build a canonical template parameter list.
267 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000268 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000269 CanonParams.reserve(Params->size());
270 for (TemplateParameterList::const_iterator P = Params->begin(),
271 PEnd = Params->end();
272 P != PEnd; ++P) {
273 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
274 CanonParams.push_back(
275 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000276 SourceLocation(),
277 SourceLocation(),
278 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000279 TTP->getIndex(), 0, false,
280 TTP->isParameterPack()));
281 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000282 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
283 QualType T = getCanonicalType(NTTP->getType());
284 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
285 NonTypeTemplateParmDecl *Param;
286 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000287 SmallVector<QualType, 2> ExpandedTypes;
288 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000289 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
290 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
291 ExpandedTInfos.push_back(
292 getTrivialTypeSourceInfo(ExpandedTypes.back()));
293 }
294
295 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000296 SourceLocation(),
297 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000298 NTTP->getDepth(),
299 NTTP->getPosition(), 0,
300 T,
301 TInfo,
302 ExpandedTypes.data(),
303 ExpandedTypes.size(),
304 ExpandedTInfos.data());
305 } else {
306 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000307 SourceLocation(),
308 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000309 NTTP->getDepth(),
310 NTTP->getPosition(), 0,
311 T,
312 NTTP->isParameterPack(),
313 TInfo);
314 }
315 CanonParams.push_back(Param);
316
317 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000318 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
319 cast<TemplateTemplateParmDecl>(*P)));
320 }
321
322 TemplateTemplateParmDecl *CanonTTP
323 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
324 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000325 TTP->getPosition(),
326 TTP->isParameterPack(),
327 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000328 TemplateParameterList::Create(*this, SourceLocation(),
329 SourceLocation(),
330 CanonParams.data(),
331 CanonParams.size(),
332 SourceLocation()));
333
334 // Get the new insert position for the node we care about.
335 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
336 assert(Canonical == 0 && "Shouldn't be in the map!");
337 (void)Canonical;
338
339 // Create the canonical template template parameter entry.
340 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
341 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
342 return CanonTTP;
343}
344
Charles Davis53c59df2010-08-16 03:33:14 +0000345CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000346 if (!LangOpts.CPlusPlus) return 0;
347
Charles Davis6bcb07a2010-08-19 02:18:14 +0000348 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000349 case CXXABI_ARM:
350 return CreateARMCXXABI(*this);
351 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000352 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000353 case CXXABI_Microsoft:
354 return CreateMicrosoftCXXABI(*this);
355 }
David Blaikie8a40f702012-01-17 06:56:22 +0000356 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000357}
358
Douglas Gregore8bbc122011-09-02 00:18:52 +0000359static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000360 const LangOptions &LOpts) {
361 if (LOpts.FakeAddressSpaceMap) {
362 // The fake address space map must have a distinct entry for each
363 // language-specific address space.
364 static const unsigned FakeAddrSpaceMap[] = {
365 1, // opencl_global
366 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000367 3, // opencl_constant
368 4, // cuda_device
369 5, // cuda_constant
370 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000371 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000372 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000373 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000374 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000375 }
376}
377
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000378ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000379 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000380 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000381 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000382 unsigned size_reserve,
383 bool DelayInitialization)
384 : FunctionProtoTypes(this_()),
385 TemplateSpecializationTypes(this_()),
386 DependentTemplateSpecializationTypes(this_()),
387 SubstTemplateTemplateParmPacks(this_()),
388 GlobalNestedNameSpecifier(0),
389 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000390 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000391 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000392 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000393 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000394 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
395 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
396 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000397 NullTypeSourceInfo(QualType()),
398 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000399 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000400 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000401 Idents(idents), Selectors(sels),
402 BuiltinInfo(builtins),
403 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000404 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000405 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000406 LastSDM(0, 0),
407 UniqueBlockByRefTypeID(0)
408{
Mike Stump11289f42009-09-09 15:08:12 +0000409 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000410 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000411
412 if (!DelayInitialization) {
413 assert(t && "No target supplied for ASTContext initialization");
414 InitBuiltinTypes(*t);
415 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000416}
417
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000418ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000419 // Release the DenseMaps associated with DeclContext objects.
420 // FIXME: Is this the ideal solution?
421 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000422
Douglas Gregor5b11d492010-07-25 17:53:33 +0000423 // Call all of the deallocation functions.
424 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
425 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000426
Ted Kremenek076baeb2010-06-08 23:00:58 +0000427 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000428 // because they can contain DenseMaps.
429 for (llvm::DenseMap<const ObjCContainerDecl*,
430 const ASTRecordLayout*>::iterator
431 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
432 // Increment in loop to prevent using deallocated memory.
433 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
434 R->Destroy(*this);
435
Ted Kremenek076baeb2010-06-08 23:00:58 +0000436 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
437 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
438 // Increment in loop to prevent using deallocated memory.
439 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
440 R->Destroy(*this);
441 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000442
443 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
444 AEnd = DeclAttrs.end();
445 A != AEnd; ++A)
446 A->second->~AttrVec();
447}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000448
Douglas Gregor1a809332010-05-23 18:26:36 +0000449void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
450 Deallocations.push_back(std::make_pair(Callback, Data));
451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000454ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000455 ExternalSource.reset(Source.take());
456}
457
Chris Lattner4eb445d2007-01-26 01:27:23 +0000458void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000459 llvm::errs() << "\n*** AST Context Stats:\n";
460 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000461
Douglas Gregora30d0462009-05-26 14:40:08 +0000462 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000463#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000464#define ABSTRACT_TYPE(Name, Parent)
465#include "clang/AST/TypeNodes.def"
466 0 // Extra
467 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000468
Chris Lattner4eb445d2007-01-26 01:27:23 +0000469 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
470 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000471 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000472 }
473
Douglas Gregora30d0462009-05-26 14:40:08 +0000474 unsigned Idx = 0;
475 unsigned TotalBytes = 0;
476#define TYPE(Name, Parent) \
477 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000478 llvm::errs() << " " << counts[Idx] << " " << #Name \
479 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000480 TotalBytes += counts[Idx] * sizeof(Name##Type); \
481 ++Idx;
482#define ABSTRACT_TYPE(Name, Parent)
483#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000484
Chandler Carruth3c147a72011-07-04 05:32:14 +0000485 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
486
Douglas Gregor7454c562010-07-02 20:37:36 +0000487 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000488 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
489 << NumImplicitDefaultConstructors
490 << " implicit default constructors created\n";
491 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
492 << NumImplicitCopyConstructors
493 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000494 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000495 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
496 << NumImplicitMoveConstructors
497 << " implicit move constructors created\n";
498 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
499 << NumImplicitCopyAssignmentOperators
500 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000501 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000502 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
503 << NumImplicitMoveAssignmentOperators
504 << " implicit move assignment operators created\n";
505 llvm::errs() << NumImplicitDestructorsDeclared << "/"
506 << NumImplicitDestructors
507 << " implicit destructors created\n";
508
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000509 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000510 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000511 ExternalSource->PrintStats();
512 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000513
Douglas Gregor5b11d492010-07-25 17:53:33 +0000514 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000515}
516
Douglas Gregor801c99d2011-08-12 06:49:56 +0000517TypedefDecl *ASTContext::getInt128Decl() const {
518 if (!Int128Decl) {
519 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
520 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
521 getTranslationUnitDecl(),
522 SourceLocation(),
523 SourceLocation(),
524 &Idents.get("__int128_t"),
525 TInfo);
526 }
527
528 return Int128Decl;
529}
530
531TypedefDecl *ASTContext::getUInt128Decl() const {
532 if (!UInt128Decl) {
533 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
534 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
535 getTranslationUnitDecl(),
536 SourceLocation(),
537 SourceLocation(),
538 &Idents.get("__uint128_t"),
539 TInfo);
540 }
541
542 return UInt128Decl;
543}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000544
John McCall48f2d582009-10-23 23:03:21 +0000545void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000546 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000547 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000548 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000549}
550
Douglas Gregore8bbc122011-09-02 00:18:52 +0000551void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
552 assert((!this->Target || this->Target == &Target) &&
553 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000554 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000555
Douglas Gregore8bbc122011-09-02 00:18:52 +0000556 this->Target = &Target;
557
558 ABI.reset(createCXXABI(Target));
559 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
560
Chris Lattner970e54e2006-11-12 00:37:36 +0000561 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000562 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattner970e54e2006-11-12 00:37:36 +0000564 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000565 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000566 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000567 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000568 InitBuiltinType(CharTy, BuiltinType::Char_S);
569 else
570 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000571 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000572 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
573 InitBuiltinType(ShortTy, BuiltinType::Short);
574 InitBuiltinType(IntTy, BuiltinType::Int);
575 InitBuiltinType(LongTy, BuiltinType::Long);
576 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattner970e54e2006-11-12 00:37:36 +0000578 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000579 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
580 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
581 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
582 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
583 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000584
Chris Lattner970e54e2006-11-12 00:37:36 +0000585 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000586 InitBuiltinType(FloatTy, BuiltinType::Float);
587 InitBuiltinType(DoubleTy, BuiltinType::Double);
588 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000589
Chris Lattnerf122cef2009-04-30 02:43:43 +0000590 // GNU extension, 128-bit integers.
591 InitBuiltinType(Int128Ty, BuiltinType::Int128);
592 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
593
Chris Lattnerad3467e2010-12-25 23:25:43 +0000594 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000595 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000596 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
597 else // -fshort-wchar makes wchar_t be unsigned.
598 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
599 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000600 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000601
James Molloy36365542012-05-04 10:55:22 +0000602 WIntTy = getFromTargetType(Target.getWIntType());
603
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000604 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
605 InitBuiltinType(Char16Ty, BuiltinType::Char16);
606 else // C99
607 Char16Ty = getFromTargetType(Target.getChar16Type());
608
609 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
610 InitBuiltinType(Char32Ty, BuiltinType::Char32);
611 else // C99
612 Char32Ty = getFromTargetType(Target.getChar32Type());
613
Douglas Gregor4619e432008-12-05 23:32:09 +0000614 // Placeholder type for type-dependent expressions whose type is
615 // completely unknown. No code should ever check a type against
616 // DependentTy and users should never see it; however, it is here to
617 // help diagnose failures to properly check for type-dependent
618 // expressions.
619 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000620
John McCall36e7fe32010-10-12 00:20:44 +0000621 // Placeholder type for functions.
622 InitBuiltinType(OverloadTy, BuiltinType::Overload);
623
John McCall0009fcc2011-04-26 20:42:42 +0000624 // Placeholder type for bound members.
625 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
626
John McCall526ab472011-10-25 17:37:35 +0000627 // Placeholder type for pseudo-objects.
628 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
629
John McCall31996342011-04-07 08:22:57 +0000630 // "any" type; useful for debugger-like clients.
631 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
632
John McCall8a6b59a2011-10-17 18:09:15 +0000633 // Placeholder type for unbridged ARC casts.
634 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
635
Chris Lattner970e54e2006-11-12 00:37:36 +0000636 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000637 FloatComplexTy = getComplexType(FloatTy);
638 DoubleComplexTy = getComplexType(DoubleTy);
639 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000640
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000641 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000642 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
643 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000644 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000645
646 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000647 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
648 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000649
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000650 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000651
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000652 // void * type
653 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000654
655 // nullptr type (C++0x 2.14.7)
656 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000657
658 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
659 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000660
661 // Builtin type used to help define __builtin_va_list.
662 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000663}
664
David Blaikie9c902b52011-09-25 23:23:43 +0000665DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000666 return SourceMgr.getDiagnostics();
667}
668
Douglas Gregor561eceb2010-08-30 16:49:28 +0000669AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
670 AttrVec *&Result = DeclAttrs[D];
671 if (!Result) {
672 void *Mem = Allocate(sizeof(AttrVec));
673 Result = new (Mem) AttrVec;
674 }
675
676 return *Result;
677}
678
679/// \brief Erase the attributes corresponding to the given declaration.
680void ASTContext::eraseDeclAttrs(const Decl *D) {
681 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
682 if (Pos != DeclAttrs.end()) {
683 Pos->second->~AttrVec();
684 DeclAttrs.erase(Pos);
685 }
686}
687
Douglas Gregor86d142a2009-10-08 07:24:58 +0000688MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000689ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000690 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000691 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000692 = InstantiatedFromStaticDataMember.find(Var);
693 if (Pos == InstantiatedFromStaticDataMember.end())
694 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000695
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000696 return Pos->second;
697}
698
Mike Stump11289f42009-09-09 15:08:12 +0000699void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000700ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000701 TemplateSpecializationKind TSK,
702 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000703 assert(Inst->isStaticDataMember() && "Not a static data member");
704 assert(Tmpl->isStaticDataMember() && "Not a static data member");
705 assert(!InstantiatedFromStaticDataMember[Inst] &&
706 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000707 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000708 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000709}
710
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000711FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
712 const FunctionDecl *FD){
713 assert(FD && "Specialization is 0");
714 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000715 = ClassScopeSpecializationPattern.find(FD);
716 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000717 return 0;
718
719 return Pos->second;
720}
721
722void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
723 FunctionDecl *Pattern) {
724 assert(FD && "Specialization is 0");
725 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000726 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000727}
728
John McCalle61f2ba2009-11-18 02:36:19 +0000729NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000730ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000731 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000732 = InstantiatedFromUsingDecl.find(UUD);
733 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000734 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000735
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000736 return Pos->second;
737}
738
739void
John McCallb96ec562009-12-04 22:46:56 +0000740ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
741 assert((isa<UsingDecl>(Pattern) ||
742 isa<UnresolvedUsingValueDecl>(Pattern) ||
743 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
744 "pattern decl is not a using decl");
745 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
746 InstantiatedFromUsingDecl[Inst] = Pattern;
747}
748
749UsingShadowDecl *
750ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
751 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
752 = InstantiatedFromUsingShadowDecl.find(Inst);
753 if (Pos == InstantiatedFromUsingShadowDecl.end())
754 return 0;
755
756 return Pos->second;
757}
758
759void
760ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
761 UsingShadowDecl *Pattern) {
762 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
763 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000764}
765
Anders Carlsson5da84842009-09-01 04:26:58 +0000766FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
767 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
768 = InstantiatedFromUnnamedFieldDecl.find(Field);
769 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
770 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000771
Anders Carlsson5da84842009-09-01 04:26:58 +0000772 return Pos->second;
773}
774
775void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
776 FieldDecl *Tmpl) {
777 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
778 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
779 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
780 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000781
Anders Carlsson5da84842009-09-01 04:26:58 +0000782 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
783}
784
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000785bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
786 const FieldDecl *LastFD) const {
787 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000788 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000789}
790
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000791bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
792 const FieldDecl *LastFD) const {
793 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000794 FD->getBitWidthValue(*this) == 0 &&
795 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000796}
797
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000798bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
799 const FieldDecl *LastFD) const {
800 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000801 FD->getBitWidthValue(*this) &&
802 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000803}
804
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000805bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000806 const FieldDecl *LastFD) const {
807 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000808 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000809}
810
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000811bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000812 const FieldDecl *LastFD) const {
813 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000814 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000815}
816
Douglas Gregor832940b2010-03-02 23:58:15 +0000817ASTContext::overridden_cxx_method_iterator
818ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
819 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
820 = OverriddenMethods.find(Method);
821 if (Pos == OverriddenMethods.end())
822 return 0;
823
824 return Pos->second.begin();
825}
826
827ASTContext::overridden_cxx_method_iterator
828ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
829 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
830 = OverriddenMethods.find(Method);
831 if (Pos == OverriddenMethods.end())
832 return 0;
833
834 return Pos->second.end();
835}
836
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000837unsigned
838ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
839 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
840 = OverriddenMethods.find(Method);
841 if (Pos == OverriddenMethods.end())
842 return 0;
843
844 return Pos->second.size();
845}
846
Douglas Gregor832940b2010-03-02 23:58:15 +0000847void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
848 const CXXMethodDecl *Overridden) {
849 OverriddenMethods[Method].push_back(Overridden);
850}
851
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000852void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
853 assert(!Import->NextLocalImport && "Import declaration already in the chain");
854 assert(!Import->isFromASTFile() && "Non-local import declaration");
855 if (!FirstLocalImport) {
856 FirstLocalImport = Import;
857 LastLocalImport = Import;
858 return;
859 }
860
861 LastLocalImport->NextLocalImport = Import;
862 LastLocalImport = Import;
863}
864
Chris Lattner53cfe802007-07-18 17:52:12 +0000865//===----------------------------------------------------------------------===//
866// Type Sizing and Analysis
867//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000868
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000869/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
870/// scalar floating point type.
871const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000872 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000873 assert(BT && "Not a floating point type!");
874 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000875 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000876 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000877 case BuiltinType::Float: return Target->getFloatFormat();
878 case BuiltinType::Double: return Target->getDoubleFormat();
879 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000880 }
881}
882
Ken Dyck160146e2010-01-27 17:10:57 +0000883/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000884/// specified decl. Note that bitfields do not have a valid alignment, so
885/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000886/// If @p RefAsPointee, references are treated like their underlying type
887/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000888CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000889 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000890
John McCall94268702010-10-08 18:24:19 +0000891 bool UseAlignAttrOnly = false;
892 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
893 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000894
John McCall94268702010-10-08 18:24:19 +0000895 // __attribute__((aligned)) can increase or decrease alignment
896 // *except* on a struct or struct member, where it only increases
897 // alignment unless 'packed' is also specified.
898 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000899 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000900 // ignore that possibility; Sema should diagnose it.
901 if (isa<FieldDecl>(D)) {
902 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
903 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
904 } else {
905 UseAlignAttrOnly = true;
906 }
907 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000908 else if (isa<FieldDecl>(D))
909 UseAlignAttrOnly =
910 D->hasAttr<PackedAttr>() ||
911 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000912
John McCall4e819612011-01-20 07:57:12 +0000913 // If we're using the align attribute only, just ignore everything
914 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000915 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000916 // do nothing
917
John McCall94268702010-10-08 18:24:19 +0000918 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000919 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000920 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000921 if (RefAsPointee)
922 T = RT->getPointeeType();
923 else
924 T = getPointerType(RT->getPointeeType());
925 }
926 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000927 // Adjust alignments of declarations with array type by the
928 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000929 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000930 const ArrayType *arrayType;
931 if (MinWidth && (arrayType = getAsArrayType(T))) {
932 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000933 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000934 else if (isa<ConstantArrayType>(arrayType) &&
935 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000936 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000937
John McCall33ddac02011-01-19 10:06:00 +0000938 // Walk through any array types while we're at it.
939 T = getBaseElementType(arrayType);
940 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000941 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000942 }
John McCall4e819612011-01-20 07:57:12 +0000943
944 // Fields can be subject to extra alignment constraints, like if
945 // the field is packed, the struct is packed, or the struct has a
946 // a max-field-alignment constraint (#pragma pack). So calculate
947 // the actual alignment of the field within the struct, and then
948 // (as we're expected to) constrain that by the alignment of the type.
949 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
950 // So calculate the alignment of the field.
951 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
952
953 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000954 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000955
956 // Use the GCD of that and the offset within the record.
957 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
958 if (offset > 0) {
959 // Alignment is always a power of 2, so the GCD will be a power of 2,
960 // which means we get to do this crazy thing instead of Euclid's.
961 uint64_t lowBitOfOffset = offset & (~offset + 1);
962 if (lowBitOfOffset < fieldAlign)
963 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
964 }
965
966 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000967 }
Chris Lattner68061312009-01-24 21:53:27 +0000968 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000969
Ken Dyckcc56c542011-01-15 18:38:59 +0000970 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000971}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000972
John McCall87fe5d52010-05-20 01:18:31 +0000973std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000974ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000975 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000976 return std::make_pair(toCharUnitsFromBits(Info.first),
977 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000978}
979
980std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000981ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000982 return getTypeInfoInChars(T.getTypePtr());
983}
984
Daniel Dunbarc6475872012-03-09 04:12:54 +0000985std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
986 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
987 if (it != MemoizedTypeInfo.end())
988 return it->second;
989
990 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
991 MemoizedTypeInfo.insert(std::make_pair(T, Info));
992 return Info;
993}
994
995/// getTypeInfoImpl - Return the size of the specified type, in bits. This
996/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000997///
998/// FIXME: Pointers into different addr spaces could have different sizes and
999/// alignment requirements: getPointerInfo should take an AddrSpace, this
1000/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001001std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001002ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001003 uint64_t Width=0;
1004 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001005 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001006#define TYPE(Class, Base)
1007#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001008#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001009#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1010#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001011 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001012
Chris Lattner355332d2007-07-13 22:27:08 +00001013 case Type::FunctionNoProto:
1014 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001015 // GCC extension: alignof(function) = 32 bits
1016 Width = 0;
1017 Align = 32;
1018 break;
1019
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001020 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001021 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001022 Width = 0;
1023 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1024 break;
1025
Steve Naroff5c131802007-08-30 01:06:46 +00001026 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001027 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Chris Lattner37e05872008-03-05 18:54:05 +00001029 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001030 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001031 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1032 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001033 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001034 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001035 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001036 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001037 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001038 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001039 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001040 const VectorType *VT = cast<VectorType>(T);
1041 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1042 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001043 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001044 // If the alignment is not a power of 2, round up to the next power of 2.
1045 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001046 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001047 Align = llvm::NextPowerOf2(Align);
1048 Width = llvm::RoundUpToAlignment(Width, Align);
1049 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001050 // Adjust the alignment based on the target max.
1051 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1052 if (TargetVectorAlign && TargetVectorAlign < Align)
1053 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001054 break;
1055 }
Chris Lattner647fb222007-07-18 18:26:58 +00001056
Chris Lattner7570e9c2008-03-08 08:52:55 +00001057 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001058 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001059 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001060 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001061 // GCC extension: alignof(void) = 8 bits.
1062 Width = 0;
1063 Align = 8;
1064 break;
1065
Chris Lattner6a4f7452007-12-19 19:23:28 +00001066 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001067 Width = Target->getBoolWidth();
1068 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001069 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001070 case BuiltinType::Char_S:
1071 case BuiltinType::Char_U:
1072 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001073 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001074 Width = Target->getCharWidth();
1075 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001076 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001077 case BuiltinType::WChar_S:
1078 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001079 Width = Target->getWCharWidth();
1080 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001081 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001082 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001083 Width = Target->getChar16Width();
1084 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001085 break;
1086 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001087 Width = Target->getChar32Width();
1088 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001089 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001090 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001091 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001092 Width = Target->getShortWidth();
1093 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001094 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001095 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001096 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001097 Width = Target->getIntWidth();
1098 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001099 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001100 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001101 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001102 Width = Target->getLongWidth();
1103 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001104 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001105 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001106 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001107 Width = Target->getLongLongWidth();
1108 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001109 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001110 case BuiltinType::Int128:
1111 case BuiltinType::UInt128:
1112 Width = 128;
1113 Align = 128; // int128_t is 128-bit aligned on all targets.
1114 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001115 case BuiltinType::Half:
1116 Width = Target->getHalfWidth();
1117 Align = Target->getHalfAlign();
1118 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001119 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001120 Width = Target->getFloatWidth();
1121 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001122 break;
1123 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001124 Width = Target->getDoubleWidth();
1125 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001126 break;
1127 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001128 Width = Target->getLongDoubleWidth();
1129 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001130 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001131 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001132 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1133 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001134 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001135 case BuiltinType::ObjCId:
1136 case BuiltinType::ObjCClass:
1137 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 Width = Target->getPointerWidth(0);
1139 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001140 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001141 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001142 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001143 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001144 Width = Target->getPointerWidth(0);
1145 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001146 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001147 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001148 unsigned AS = getTargetAddressSpace(
1149 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001150 Width = Target->getPointerWidth(AS);
1151 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001152 break;
1153 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001154 case Type::LValueReference:
1155 case Type::RValueReference: {
1156 // alignof and sizeof should never enter this code path here, so we go
1157 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001158 unsigned AS = getTargetAddressSpace(
1159 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001160 Width = Target->getPointerWidth(AS);
1161 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001162 break;
1163 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001164 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001165 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001166 Width = Target->getPointerWidth(AS);
1167 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001168 break;
1169 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001170 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001171 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001172 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001173 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001174 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001175 Align = PtrDiffInfo.second;
1176 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001177 }
Chris Lattner647fb222007-07-18 18:26:58 +00001178 case Type::Complex: {
1179 // Complex types have the same alignment as their elements, but twice the
1180 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001181 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001182 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001183 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001184 Align = EltInfo.second;
1185 break;
1186 }
John McCall8b07ec22010-05-15 11:32:37 +00001187 case Type::ObjCObject:
1188 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001189 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001190 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001191 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001192 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001193 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001194 break;
1195 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001196 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001197 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001198 const TagType *TT = cast<TagType>(T);
1199
1200 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001201 Width = 8;
1202 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001203 break;
1204 }
Mike Stump11289f42009-09-09 15:08:12 +00001205
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001206 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001207 return getTypeInfo(ET->getDecl()->getIntegerType());
1208
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001209 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001210 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001211 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001212 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001213 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001214 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001215
Chris Lattner63d2b362009-10-22 05:17:15 +00001216 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001217 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1218 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001219
Richard Smith30482bc2011-02-20 03:19:35 +00001220 case Type::Auto: {
1221 const AutoType *A = cast<AutoType>(T);
1222 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001223 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001224 }
1225
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001226 case Type::Paren:
1227 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1228
Douglas Gregoref462e62009-04-30 17:32:17 +00001229 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001230 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001231 std::pair<uint64_t, unsigned> Info
1232 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001233 // If the typedef has an aligned attribute on it, it overrides any computed
1234 // alignment we have. This violates the GCC documentation (which says that
1235 // attribute(aligned) can only round up) but matches its implementation.
1236 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1237 Align = AttrAlign;
1238 else
1239 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001240 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001241 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001242 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001243
1244 case Type::TypeOfExpr:
1245 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1246 .getTypePtr());
1247
1248 case Type::TypeOf:
1249 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1250
Anders Carlsson81df7b82009-06-24 19:06:50 +00001251 case Type::Decltype:
1252 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1253 .getTypePtr());
1254
Alexis Hunte852b102011-05-24 22:41:36 +00001255 case Type::UnaryTransform:
1256 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1257
Abramo Bagnara6150c882010-05-11 21:36:43 +00001258 case Type::Elaborated:
1259 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001260
John McCall81904512011-01-06 01:58:22 +00001261 case Type::Attributed:
1262 return getTypeInfo(
1263 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1264
Richard Smith3f1b5d02011-05-05 21:57:07 +00001265 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001266 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001267 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001268 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1269 // A type alias template specialization may refer to a typedef with the
1270 // aligned attribute on it.
1271 if (TST->isTypeAlias())
1272 return getTypeInfo(TST->getAliasedType().getTypePtr());
1273 else
1274 return getTypeInfo(getCanonicalType(T));
1275 }
1276
Eli Friedman0dfb8892011-10-06 23:00:33 +00001277 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001278 std::pair<uint64_t, unsigned> Info
1279 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1280 Width = Info.first;
1281 Align = Info.second;
1282 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1283 llvm::isPowerOf2_64(Width)) {
1284 // We can potentially perform lock-free atomic operations for this
1285 // type; promote the alignment appropriately.
1286 // FIXME: We could potentially promote the width here as well...
1287 // is that worthwhile? (Non-struct atomic types generally have
1288 // power-of-two size anyway, but structs might not. Requires a bit
1289 // of implementation work to make sure we zero out the extra bits.)
1290 Align = static_cast<unsigned>(Width);
1291 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001292 }
1293
Douglas Gregoref462e62009-04-30 17:32:17 +00001294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001296 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001297 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001298}
1299
Ken Dyckcc56c542011-01-15 18:38:59 +00001300/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1301CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1302 return CharUnits::fromQuantity(BitSize / getCharWidth());
1303}
1304
Ken Dyckb0fcc592011-02-11 01:54:29 +00001305/// toBits - Convert a size in characters to a size in characters.
1306int64_t ASTContext::toBits(CharUnits CharSize) const {
1307 return CharSize.getQuantity() * getCharWidth();
1308}
1309
Ken Dyck8c89d592009-12-22 14:23:30 +00001310/// getTypeSizeInChars - Return the size of the specified type, in characters.
1311/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001312CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001313 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001314}
Jay Foad39c79802011-01-12 09:06:06 +00001315CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001316 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001317}
1318
Ken Dycka6046ab2010-01-26 17:25:18 +00001319/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001320/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001321CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001322 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001323}
Jay Foad39c79802011-01-12 09:06:06 +00001324CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001325 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001326}
1327
Chris Lattnera3402cd2009-01-27 18:08:34 +00001328/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1329/// type for the current target in bits. This can be different than the ABI
1330/// alignment in cases where it is beneficial for performance to overalign
1331/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001332unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001333 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001334
1335 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001336 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001337 T = CT->getElementType().getTypePtr();
1338 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001339 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1340 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001341 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1342
Chris Lattnera3402cd2009-01-27 18:08:34 +00001343 return ABIAlign;
1344}
1345
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001346/// DeepCollectObjCIvars -
1347/// This routine first collects all declared, but not synthesized, ivars in
1348/// super class and then collects all ivars, including those synthesized for
1349/// current class. This routine is used for implementation of current class
1350/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001351///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001352void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1353 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001354 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001355 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1356 DeepCollectObjCIvars(SuperClass, false, Ivars);
1357 if (!leafClass) {
1358 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1359 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001360 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001361 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001362 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001363 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001364 Iv= Iv->getNextIvar())
1365 Ivars.push_back(Iv);
1366 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001367}
1368
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001369/// CollectInheritedProtocols - Collect all protocols in current class and
1370/// those inherited by it.
1371void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001372 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001373 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001374 // We can use protocol_iterator here instead of
1375 // all_referenced_protocol_iterator since we are walking all categories.
1376 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1377 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001378 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001379 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001380 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001381 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001382 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001383 CollectInheritedProtocols(*P, Protocols);
1384 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001385 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001386
1387 // Categories of this Interface.
1388 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1389 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1390 CollectInheritedProtocols(CDeclChain, Protocols);
1391 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1392 while (SD) {
1393 CollectInheritedProtocols(SD, Protocols);
1394 SD = SD->getSuperClass();
1395 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001396 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001397 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001398 PE = OC->protocol_end(); P != PE; ++P) {
1399 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001400 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001401 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1402 PE = Proto->protocol_end(); P != PE; ++P)
1403 CollectInheritedProtocols(*P, Protocols);
1404 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001405 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001406 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1407 PE = OP->protocol_end(); P != PE; ++P) {
1408 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001409 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001410 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1411 PE = Proto->protocol_end(); P != PE; ++P)
1412 CollectInheritedProtocols(*P, Protocols);
1413 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001414 }
1415}
1416
Jay Foad39c79802011-01-12 09:06:06 +00001417unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001418 unsigned count = 0;
1419 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001420 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1421 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001422 count += CDecl->ivar_size();
1423
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001424 // Count ivar defined in this class's implementation. This
1425 // includes synthesized ivars.
1426 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001427 count += ImplDecl->ivar_size();
1428
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001429 return count;
1430}
1431
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001432bool ASTContext::isSentinelNullExpr(const Expr *E) {
1433 if (!E)
1434 return false;
1435
1436 // nullptr_t is always treated as null.
1437 if (E->getType()->isNullPtrType()) return true;
1438
1439 if (E->getType()->isAnyPointerType() &&
1440 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1441 Expr::NPC_ValueDependentIsNull))
1442 return true;
1443
1444 // Unfortunately, __null has type 'int'.
1445 if (isa<GNUNullExpr>(E)) return true;
1446
1447 return false;
1448}
1449
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001450/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1451ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1452 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1453 I = ObjCImpls.find(D);
1454 if (I != ObjCImpls.end())
1455 return cast<ObjCImplementationDecl>(I->second);
1456 return 0;
1457}
1458/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1459ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1460 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1461 I = ObjCImpls.find(D);
1462 if (I != ObjCImpls.end())
1463 return cast<ObjCCategoryImplDecl>(I->second);
1464 return 0;
1465}
1466
1467/// \brief Set the implementation of ObjCInterfaceDecl.
1468void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1469 ObjCImplementationDecl *ImplD) {
1470 assert(IFaceD && ImplD && "Passed null params");
1471 ObjCImpls[IFaceD] = ImplD;
1472}
1473/// \brief Set the implementation of ObjCCategoryDecl.
1474void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1475 ObjCCategoryImplDecl *ImplD) {
1476 assert(CatD && ImplD && "Passed null params");
1477 ObjCImpls[CatD] = ImplD;
1478}
1479
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001480ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1481 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1482 return ID;
1483 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1484 return CD->getClassInterface();
1485 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1486 return IMD->getClassInterface();
1487
1488 return 0;
1489}
1490
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001491/// \brief Get the copy initialization expression of VarDecl,or NULL if
1492/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001493Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001494 assert(VD && "Passed null params");
1495 assert(VD->hasAttr<BlocksAttr>() &&
1496 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001497 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001498 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001499 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1500}
1501
1502/// \brief Set the copy inialization expression of a block var decl.
1503void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1504 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001505 assert(VD->hasAttr<BlocksAttr>() &&
1506 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001507 BlockVarCopyInits[VD] = Init;
1508}
1509
John McCallbcd03502009-12-07 02:54:59 +00001510TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001511 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001512 if (!DataSize)
1513 DataSize = TypeLoc::getFullDataSizeForType(T);
1514 else
1515 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001516 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001517
John McCallbcd03502009-12-07 02:54:59 +00001518 TypeSourceInfo *TInfo =
1519 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1520 new (TInfo) TypeSourceInfo(T);
1521 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001522}
1523
John McCallbcd03502009-12-07 02:54:59 +00001524TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001525 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001526 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001527 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001528 return DI;
1529}
1530
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001531const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001532ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001533 return getObjCLayout(D, 0);
1534}
1535
1536const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001537ASTContext::getASTObjCImplementationLayout(
1538 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001539 return getObjCLayout(D->getClassInterface(), D);
1540}
1541
Chris Lattner983a8bb2007-07-13 22:13:22 +00001542//===----------------------------------------------------------------------===//
1543// Type creation/memoization methods
1544//===----------------------------------------------------------------------===//
1545
Jay Foad39c79802011-01-12 09:06:06 +00001546QualType
John McCall33ddac02011-01-19 10:06:00 +00001547ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1548 unsigned fastQuals = quals.getFastQualifiers();
1549 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001550
1551 // Check if we've already instantiated this type.
1552 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001553 ExtQuals::Profile(ID, baseType, quals);
1554 void *insertPos = 0;
1555 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1556 assert(eq->getQualifiers() == quals);
1557 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001558 }
1559
John McCall33ddac02011-01-19 10:06:00 +00001560 // If the base type is not canonical, make the appropriate canonical type.
1561 QualType canon;
1562 if (!baseType->isCanonicalUnqualified()) {
1563 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001564 canonSplit.Quals.addConsistentQualifiers(quals);
1565 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001566
1567 // Re-find the insert position.
1568 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1569 }
1570
1571 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1572 ExtQualNodes.InsertNode(eq, insertPos);
1573 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001574}
1575
Jay Foad39c79802011-01-12 09:06:06 +00001576QualType
1577ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001578 QualType CanT = getCanonicalType(T);
1579 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001580 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001581
John McCall8ccfcb52009-09-24 19:53:00 +00001582 // If we are composing extended qualifiers together, merge together
1583 // into one ExtQuals node.
1584 QualifierCollector Quals;
1585 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall8ccfcb52009-09-24 19:53:00 +00001587 // If this type already has an address space specified, it cannot get
1588 // another one.
1589 assert(!Quals.hasAddressSpace() &&
1590 "Type cannot be in multiple addr spaces!");
1591 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCall8ccfcb52009-09-24 19:53:00 +00001593 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001594}
1595
Chris Lattnerd60183d2009-02-18 22:53:11 +00001596QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001597 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001598 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001599 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001600 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001601
John McCall53fa7142010-12-24 02:08:15 +00001602 if (const PointerType *ptr = T->getAs<PointerType>()) {
1603 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001604 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001605 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1606 return getPointerType(ResultType);
1607 }
1608 }
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCall8ccfcb52009-09-24 19:53:00 +00001610 // If we are composing extended qualifiers together, merge together
1611 // into one ExtQuals node.
1612 QualifierCollector Quals;
1613 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001614
John McCall8ccfcb52009-09-24 19:53:00 +00001615 // If this type already has an ObjCGC specified, it cannot get
1616 // another one.
1617 assert(!Quals.hasObjCGCAttr() &&
1618 "Type cannot have multiple ObjCGCs!");
1619 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall8ccfcb52009-09-24 19:53:00 +00001621 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001622}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001623
John McCall4f5019e2010-12-19 02:44:49 +00001624const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1625 FunctionType::ExtInfo Info) {
1626 if (T->getExtInfo() == Info)
1627 return T;
1628
1629 QualType Result;
1630 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1631 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1632 } else {
1633 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1634 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1635 EPI.ExtInfo = Info;
1636 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1637 FPT->getNumArgs(), EPI);
1638 }
1639
1640 return cast<FunctionType>(Result.getTypePtr());
1641}
1642
Chris Lattnerc6395932007-06-22 20:56:16 +00001643/// getComplexType - Return the uniqued reference to the type for a complex
1644/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001645QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001646 // Unique pointers, to guarantee there is only one pointer of a particular
1647 // structure.
1648 llvm::FoldingSetNodeID ID;
1649 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattnerc6395932007-06-22 20:56:16 +00001651 void *InsertPos = 0;
1652 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1653 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattnerc6395932007-06-22 20:56:16 +00001655 // If the pointee type isn't canonical, this won't be a canonical type either,
1656 // so fill in the canonical type field.
1657 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001658 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001659 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001660
Chris Lattnerc6395932007-06-22 20:56:16 +00001661 // Get the new insert position for the node we care about.
1662 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001663 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001664 }
John McCall90d1c2d2009-09-24 23:30:46 +00001665 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001666 Types.push_back(New);
1667 ComplexTypes.InsertNode(New, InsertPos);
1668 return QualType(New, 0);
1669}
1670
Chris Lattner970e54e2006-11-12 00:37:36 +00001671/// getPointerType - Return the uniqued reference to the type for a pointer to
1672/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001673QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001674 // Unique pointers, to guarantee there is only one pointer of a particular
1675 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001676 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001677 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattner67521df2007-01-27 01:29:36 +00001679 void *InsertPos = 0;
1680 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001681 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattner7ccecb92006-11-12 08:50:50 +00001683 // If the pointee type isn't canonical, this won't be a canonical type either,
1684 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001685 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001686 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001687 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattner67521df2007-01-27 01:29:36 +00001689 // Get the new insert position for the node we care about.
1690 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001691 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001692 }
John McCall90d1c2d2009-09-24 23:30:46 +00001693 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001694 Types.push_back(New);
1695 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001696 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001697}
1698
Mike Stump11289f42009-09-09 15:08:12 +00001699/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001700/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001701QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001702 assert(T->isFunctionType() && "block of function types only");
1703 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001704 // structure.
1705 llvm::FoldingSetNodeID ID;
1706 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001707
Steve Naroffec33ed92008-08-27 16:04:49 +00001708 void *InsertPos = 0;
1709 if (BlockPointerType *PT =
1710 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1711 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001712
1713 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001714 // type either so fill in the canonical type field.
1715 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001716 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001717 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001718
Steve Naroffec33ed92008-08-27 16:04:49 +00001719 // Get the new insert position for the node we care about.
1720 BlockPointerType *NewIP =
1721 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001722 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001723 }
John McCall90d1c2d2009-09-24 23:30:46 +00001724 BlockPointerType *New
1725 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001726 Types.push_back(New);
1727 BlockPointerTypes.InsertNode(New, InsertPos);
1728 return QualType(New, 0);
1729}
1730
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001731/// getLValueReferenceType - Return the uniqued reference to the type for an
1732/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001733QualType
1734ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001735 assert(getCanonicalType(T) != OverloadTy &&
1736 "Unresolved overloaded function type");
1737
Bill Wendling3708c182007-05-27 10:15:43 +00001738 // Unique pointers, to guarantee there is only one pointer of a particular
1739 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001740 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001741 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001742
1743 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001744 if (LValueReferenceType *RT =
1745 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001746 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001747
John McCallfc93cf92009-10-22 22:37:11 +00001748 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1749
Bill Wendling3708c182007-05-27 10:15:43 +00001750 // If the referencee type isn't canonical, this won't be a canonical type
1751 // either, so fill in the canonical type field.
1752 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001753 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1754 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1755 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001756
Bill Wendling3708c182007-05-27 10:15:43 +00001757 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001758 LValueReferenceType *NewIP =
1759 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001760 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001761 }
1762
John McCall90d1c2d2009-09-24 23:30:46 +00001763 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001764 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1765 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001766 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001767 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001768
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001769 return QualType(New, 0);
1770}
1771
1772/// getRValueReferenceType - Return the uniqued reference to the type for an
1773/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001774QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001775 // Unique pointers, to guarantee there is only one pointer of a particular
1776 // structure.
1777 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001778 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001779
1780 void *InsertPos = 0;
1781 if (RValueReferenceType *RT =
1782 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1783 return QualType(RT, 0);
1784
John McCallfc93cf92009-10-22 22:37:11 +00001785 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1786
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001787 // If the referencee type isn't canonical, this won't be a canonical type
1788 // either, so fill in the canonical type field.
1789 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001790 if (InnerRef || !T.isCanonical()) {
1791 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1792 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001793
1794 // Get the new insert position for the node we care about.
1795 RValueReferenceType *NewIP =
1796 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001797 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001798 }
1799
John McCall90d1c2d2009-09-24 23:30:46 +00001800 RValueReferenceType *New
1801 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001802 Types.push_back(New);
1803 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001804 return QualType(New, 0);
1805}
1806
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001807/// getMemberPointerType - Return the uniqued reference to the type for a
1808/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001809QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001810 // Unique pointers, to guarantee there is only one pointer of a particular
1811 // structure.
1812 llvm::FoldingSetNodeID ID;
1813 MemberPointerType::Profile(ID, T, Cls);
1814
1815 void *InsertPos = 0;
1816 if (MemberPointerType *PT =
1817 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1818 return QualType(PT, 0);
1819
1820 // If the pointee or class type isn't canonical, this won't be a canonical
1821 // type either, so fill in the canonical type field.
1822 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001823 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001824 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1825
1826 // Get the new insert position for the node we care about.
1827 MemberPointerType *NewIP =
1828 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001829 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001830 }
John McCall90d1c2d2009-09-24 23:30:46 +00001831 MemberPointerType *New
1832 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001833 Types.push_back(New);
1834 MemberPointerTypes.InsertNode(New, InsertPos);
1835 return QualType(New, 0);
1836}
1837
Mike Stump11289f42009-09-09 15:08:12 +00001838/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001839/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001840QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001841 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001842 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001843 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001844 assert((EltTy->isDependentType() ||
1845 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001846 "Constant array of VLAs is illegal!");
1847
Chris Lattnere2df3f92009-05-13 04:12:56 +00001848 // Convert the array size into a canonical width matching the pointer size for
1849 // the target.
1850 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001851 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001852 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001853
Chris Lattner23b7eb62007-06-15 23:05:46 +00001854 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001855 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001856
Chris Lattner36f8e652007-01-27 08:31:04 +00001857 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001858 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001859 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001860 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001861
John McCall33ddac02011-01-19 10:06:00 +00001862 // If the element type isn't canonical or has qualifiers, this won't
1863 // be a canonical type either, so fill in the canonical type field.
1864 QualType Canon;
1865 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1866 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001867 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001868 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001869 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001870
Chris Lattner36f8e652007-01-27 08:31:04 +00001871 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001872 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001873 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001874 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001875 }
Mike Stump11289f42009-09-09 15:08:12 +00001876
John McCall90d1c2d2009-09-24 23:30:46 +00001877 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001878 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001879 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001880 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001881 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001882}
1883
John McCall06549462011-01-18 08:40:38 +00001884/// getVariableArrayDecayedType - Turns the given type, which may be
1885/// variably-modified, into the corresponding type with all the known
1886/// sizes replaced with [*].
1887QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1888 // Vastly most common case.
1889 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001890
John McCall06549462011-01-18 08:40:38 +00001891 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001892
John McCall06549462011-01-18 08:40:38 +00001893 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001894 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001895 switch (ty->getTypeClass()) {
1896#define TYPE(Class, Base)
1897#define ABSTRACT_TYPE(Class, Base)
1898#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1899#include "clang/AST/TypeNodes.def"
1900 llvm_unreachable("didn't desugar past all non-canonical types?");
1901
1902 // These types should never be variably-modified.
1903 case Type::Builtin:
1904 case Type::Complex:
1905 case Type::Vector:
1906 case Type::ExtVector:
1907 case Type::DependentSizedExtVector:
1908 case Type::ObjCObject:
1909 case Type::ObjCInterface:
1910 case Type::ObjCObjectPointer:
1911 case Type::Record:
1912 case Type::Enum:
1913 case Type::UnresolvedUsing:
1914 case Type::TypeOfExpr:
1915 case Type::TypeOf:
1916 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001917 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001918 case Type::DependentName:
1919 case Type::InjectedClassName:
1920 case Type::TemplateSpecialization:
1921 case Type::DependentTemplateSpecialization:
1922 case Type::TemplateTypeParm:
1923 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001924 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001925 case Type::PackExpansion:
1926 llvm_unreachable("type should never be variably-modified");
1927
1928 // These types can be variably-modified but should never need to
1929 // further decay.
1930 case Type::FunctionNoProto:
1931 case Type::FunctionProto:
1932 case Type::BlockPointer:
1933 case Type::MemberPointer:
1934 return type;
1935
1936 // These types can be variably-modified. All these modifications
1937 // preserve structure except as noted by comments.
1938 // TODO: if we ever care about optimizing VLAs, there are no-op
1939 // optimizations available here.
1940 case Type::Pointer:
1941 result = getPointerType(getVariableArrayDecayedType(
1942 cast<PointerType>(ty)->getPointeeType()));
1943 break;
1944
1945 case Type::LValueReference: {
1946 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1947 result = getLValueReferenceType(
1948 getVariableArrayDecayedType(lv->getPointeeType()),
1949 lv->isSpelledAsLValue());
1950 break;
1951 }
1952
1953 case Type::RValueReference: {
1954 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1955 result = getRValueReferenceType(
1956 getVariableArrayDecayedType(lv->getPointeeType()));
1957 break;
1958 }
1959
Eli Friedman0dfb8892011-10-06 23:00:33 +00001960 case Type::Atomic: {
1961 const AtomicType *at = cast<AtomicType>(ty);
1962 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1963 break;
1964 }
1965
John McCall06549462011-01-18 08:40:38 +00001966 case Type::ConstantArray: {
1967 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1968 result = getConstantArrayType(
1969 getVariableArrayDecayedType(cat->getElementType()),
1970 cat->getSize(),
1971 cat->getSizeModifier(),
1972 cat->getIndexTypeCVRQualifiers());
1973 break;
1974 }
1975
1976 case Type::DependentSizedArray: {
1977 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1978 result = getDependentSizedArrayType(
1979 getVariableArrayDecayedType(dat->getElementType()),
1980 dat->getSizeExpr(),
1981 dat->getSizeModifier(),
1982 dat->getIndexTypeCVRQualifiers(),
1983 dat->getBracketsRange());
1984 break;
1985 }
1986
1987 // Turn incomplete types into [*] types.
1988 case Type::IncompleteArray: {
1989 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1990 result = getVariableArrayType(
1991 getVariableArrayDecayedType(iat->getElementType()),
1992 /*size*/ 0,
1993 ArrayType::Normal,
1994 iat->getIndexTypeCVRQualifiers(),
1995 SourceRange());
1996 break;
1997 }
1998
1999 // Turn VLA types into [*] types.
2000 case Type::VariableArray: {
2001 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2002 result = getVariableArrayType(
2003 getVariableArrayDecayedType(vat->getElementType()),
2004 /*size*/ 0,
2005 ArrayType::Star,
2006 vat->getIndexTypeCVRQualifiers(),
2007 vat->getBracketsRange());
2008 break;
2009 }
2010 }
2011
2012 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002013 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002014}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002015
Steve Naroffcadebd02007-08-30 18:14:25 +00002016/// getVariableArrayType - Returns a non-unique reference to the type for a
2017/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002018QualType ASTContext::getVariableArrayType(QualType EltTy,
2019 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002020 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002021 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002022 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002023 // Since we don't unique expressions, it isn't possible to unique VLA's
2024 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002025 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002026
John McCall33ddac02011-01-19 10:06:00 +00002027 // Be sure to pull qualifiers off the element type.
2028 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2029 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002030 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002031 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002032 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002033 }
2034
John McCall90d1c2d2009-09-24 23:30:46 +00002035 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002036 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002037
2038 VariableArrayTypes.push_back(New);
2039 Types.push_back(New);
2040 return QualType(New, 0);
2041}
2042
Douglas Gregor4619e432008-12-05 23:32:09 +00002043/// getDependentSizedArrayType - Returns a non-unique reference to
2044/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002045/// type.
John McCall33ddac02011-01-19 10:06:00 +00002046QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2047 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002048 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002049 unsigned elementTypeQuals,
2050 SourceRange brackets) const {
2051 assert((!numElements || numElements->isTypeDependent() ||
2052 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002053 "Size must be type- or value-dependent!");
2054
John McCall33ddac02011-01-19 10:06:00 +00002055 // Dependently-sized array types that do not have a specified number
2056 // of elements will have their sizes deduced from a dependent
2057 // initializer. We do no canonicalization here at all, which is okay
2058 // because they can't be used in most locations.
2059 if (!numElements) {
2060 DependentSizedArrayType *newType
2061 = new (*this, TypeAlignment)
2062 DependentSizedArrayType(*this, elementType, QualType(),
2063 numElements, ASM, elementTypeQuals,
2064 brackets);
2065 Types.push_back(newType);
2066 return QualType(newType, 0);
2067 }
2068
2069 // Otherwise, we actually build a new type every time, but we
2070 // also build a canonical type.
2071
2072 SplitQualType canonElementType = getCanonicalType(elementType).split();
2073
2074 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002075 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002076 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002077 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002078 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002079
John McCall33ddac02011-01-19 10:06:00 +00002080 // Look for an existing type with these properties.
2081 DependentSizedArrayType *canonTy =
2082 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002083
John McCall33ddac02011-01-19 10:06:00 +00002084 // If we don't have one, build one.
2085 if (!canonTy) {
2086 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002087 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002088 QualType(), numElements, ASM, elementTypeQuals,
2089 brackets);
2090 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2091 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002092 }
2093
John McCall33ddac02011-01-19 10:06:00 +00002094 // Apply qualifiers from the element type to the array.
2095 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002096 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002097
John McCall33ddac02011-01-19 10:06:00 +00002098 // If we didn't need extra canonicalization for the element type,
2099 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002100 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002101 return canon;
2102
2103 // Otherwise, we need to build a type which follows the spelling
2104 // of the element type.
2105 DependentSizedArrayType *sugaredType
2106 = new (*this, TypeAlignment)
2107 DependentSizedArrayType(*this, elementType, canon, numElements,
2108 ASM, elementTypeQuals, brackets);
2109 Types.push_back(sugaredType);
2110 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002111}
2112
John McCall33ddac02011-01-19 10:06:00 +00002113QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002114 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002115 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002116 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002117 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002118
John McCall33ddac02011-01-19 10:06:00 +00002119 void *insertPos = 0;
2120 if (IncompleteArrayType *iat =
2121 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2122 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002123
2124 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002125 // either, so fill in the canonical type field. We also have to pull
2126 // qualifiers off the element type.
2127 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002128
John McCall33ddac02011-01-19 10:06:00 +00002129 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2130 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002131 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002132 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002133 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002134
2135 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002136 IncompleteArrayType *existing =
2137 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2138 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002139 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002140
John McCall33ddac02011-01-19 10:06:00 +00002141 IncompleteArrayType *newType = new (*this, TypeAlignment)
2142 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002143
John McCall33ddac02011-01-19 10:06:00 +00002144 IncompleteArrayTypes.InsertNode(newType, insertPos);
2145 Types.push_back(newType);
2146 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002147}
2148
Steve Naroff91fcddb2007-07-18 18:00:27 +00002149/// getVectorType - Return the unique reference to a vector type of
2150/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002151QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002152 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002153 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002154
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002155 // Check if we've already instantiated a vector of this type.
2156 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002157 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002158
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002159 void *InsertPos = 0;
2160 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2161 return QualType(VTP, 0);
2162
2163 // If the element type isn't canonical, this won't be a canonical type either,
2164 // so fill in the canonical type field.
2165 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002166 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002167 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002168
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002169 // Get the new insert position for the node we care about.
2170 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002171 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002172 }
John McCall90d1c2d2009-09-24 23:30:46 +00002173 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002174 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002175 VectorTypes.InsertNode(New, InsertPos);
2176 Types.push_back(New);
2177 return QualType(New, 0);
2178}
2179
Nate Begemance4d7fc2008-04-18 23:10:10 +00002180/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002181/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002182QualType
2183ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002184 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002185
Steve Naroff91fcddb2007-07-18 18:00:27 +00002186 // Check if we've already instantiated a vector of this type.
2187 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002188 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002189 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002190 void *InsertPos = 0;
2191 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2192 return QualType(VTP, 0);
2193
2194 // If the element type isn't canonical, this won't be a canonical type either,
2195 // so fill in the canonical type field.
2196 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002197 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002198 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Steve Naroff91fcddb2007-07-18 18:00:27 +00002200 // Get the new insert position for the node we care about.
2201 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002203 }
John McCall90d1c2d2009-09-24 23:30:46 +00002204 ExtVectorType *New = new (*this, TypeAlignment)
2205 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002206 VectorTypes.InsertNode(New, InsertPos);
2207 Types.push_back(New);
2208 return QualType(New, 0);
2209}
2210
Jay Foad39c79802011-01-12 09:06:06 +00002211QualType
2212ASTContext::getDependentSizedExtVectorType(QualType vecType,
2213 Expr *SizeExpr,
2214 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002215 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002216 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002217 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002218
Douglas Gregor352169a2009-07-31 03:54:25 +00002219 void *InsertPos = 0;
2220 DependentSizedExtVectorType *Canon
2221 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 DependentSizedExtVectorType *New;
2223 if (Canon) {
2224 // We already have a canonical version of this array type; use it as
2225 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002226 New = new (*this, TypeAlignment)
2227 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2228 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002229 } else {
2230 QualType CanonVecTy = getCanonicalType(vecType);
2231 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002232 New = new (*this, TypeAlignment)
2233 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2234 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002235
2236 DependentSizedExtVectorType *CanonCheck
2237 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2238 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2239 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002240 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2241 } else {
2242 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2243 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002244 New = new (*this, TypeAlignment)
2245 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002246 }
2247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregor758a8692009-06-17 21:51:59 +00002249 Types.push_back(New);
2250 return QualType(New, 0);
2251}
2252
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002253/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002254///
Jay Foad39c79802011-01-12 09:06:06 +00002255QualType
2256ASTContext::getFunctionNoProtoType(QualType ResultTy,
2257 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002258 const CallingConv DefaultCC = Info.getCC();
2259 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2260 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002261 // Unique functions, to guarantee there is only one function of a particular
2262 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002263 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002264 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002265
Chris Lattner47955de2007-01-27 08:37:20 +00002266 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002267 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002268 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002269 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002271 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002272 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002273 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002274 Canonical =
2275 getFunctionNoProtoType(getCanonicalType(ResultTy),
2276 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattner47955de2007-01-27 08:37:20 +00002278 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002279 FunctionNoProtoType *NewIP =
2280 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002281 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002282 }
Mike Stump11289f42009-09-09 15:08:12 +00002283
Roman Divacky65b88cd2011-03-01 17:40:53 +00002284 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002285 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002286 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002287 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002288 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002289 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002290}
2291
2292/// getFunctionType - Return a normal function type with a typed argument
2293/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002294QualType
2295ASTContext::getFunctionType(QualType ResultTy,
2296 const QualType *ArgArray, unsigned NumArgs,
2297 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002298 // Unique functions, to guarantee there is only one function of a particular
2299 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002300 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002301 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002302
2303 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002304 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002305 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002306 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002307
2308 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002309 bool isCanonical =
2310 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2311 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002312 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002313 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002314 isCanonical = false;
2315
Roman Divacky65b88cd2011-03-01 17:40:53 +00002316 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2317 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2318 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002319
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002320 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002321 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002322 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002323 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002324 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002325 CanonicalArgs.reserve(NumArgs);
2326 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002327 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002328
John McCalldb40c7f2010-12-14 08:05:40 +00002329 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002330 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002331 CanonicalEPI.ExceptionSpecType = EST_None;
2332 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002333 CanonicalEPI.ExtInfo
2334 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2335
Chris Lattner76a00cf2008-04-06 22:59:24 +00002336 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002337 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002338 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002339
Chris Lattnerfd4de792007-01-27 01:15:32 +00002340 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002341 FunctionProtoType *NewIP =
2342 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002343 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002344 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002345
John McCall31168b02011-06-15 23:02:42 +00002346 // FunctionProtoType objects are allocated with extra bytes after
2347 // them for three variable size arrays at the end:
2348 // - parameter types
2349 // - exception types
2350 // - consumed-arguments flags
2351 // Instead of the exception types, there could be a noexcept
2352 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002353 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002354 NumArgs * sizeof(QualType);
2355 if (EPI.ExceptionSpecType == EST_Dynamic)
2356 Size += EPI.NumExceptions * sizeof(QualType);
2357 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002358 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002359 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002360 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002361 }
John McCall31168b02011-06-15 23:02:42 +00002362 if (EPI.ConsumedArguments)
2363 Size += NumArgs * sizeof(bool);
2364
John McCalldb40c7f2010-12-14 08:05:40 +00002365 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002366 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2367 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002368 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002369 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002370 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002371 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002372}
Chris Lattneref51c202006-11-10 07:17:23 +00002373
John McCalle78aac42010-03-10 03:28:59 +00002374#ifndef NDEBUG
2375static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2376 if (!isa<CXXRecordDecl>(D)) return false;
2377 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2378 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2379 return true;
2380 if (RD->getDescribedClassTemplate() &&
2381 !isa<ClassTemplateSpecializationDecl>(RD))
2382 return true;
2383 return false;
2384}
2385#endif
2386
2387/// getInjectedClassNameType - Return the unique reference to the
2388/// injected class name type for the specified templated declaration.
2389QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002390 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002391 assert(NeedsInjectedClassNameType(Decl));
2392 if (Decl->TypeForDecl) {
2393 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002394 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002395 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2396 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2397 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2398 } else {
John McCall424cec92011-01-19 06:33:43 +00002399 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002400 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002401 Decl->TypeForDecl = newType;
2402 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002403 }
2404 return QualType(Decl->TypeForDecl, 0);
2405}
2406
Douglas Gregor83a586e2008-04-13 21:07:44 +00002407/// getTypeDeclType - Return the unique reference to the type for the
2408/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002409QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002410 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002411 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002412
Richard Smithdda56e42011-04-15 14:24:37 +00002413 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002414 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002415
John McCall96f0b5f2010-03-10 06:48:02 +00002416 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2417 "Template type parameter types are always available.");
2418
John McCall81e38502010-02-16 03:57:14 +00002419 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002420 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002421 "struct/union has previous declaration");
2422 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002423 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002424 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002425 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002426 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002427 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002428 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002429 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002430 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2431 Decl->TypeForDecl = newType;
2432 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002433 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002434 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002435
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002436 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002437}
2438
Chris Lattner32d920b2007-01-26 02:01:53 +00002439/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002440/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002441QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002442ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2443 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002444 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002445
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002446 if (Canonical.isNull())
2447 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002448 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002449 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002450 Decl->TypeForDecl = newType;
2451 Types.push_back(newType);
2452 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002453}
2454
Jay Foad39c79802011-01-12 09:06:06 +00002455QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002456 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2457
Douglas Gregorec9fd132012-01-14 16:38:05 +00002458 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002459 if (PrevDecl->TypeForDecl)
2460 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2461
John McCall424cec92011-01-19 06:33:43 +00002462 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2463 Decl->TypeForDecl = newType;
2464 Types.push_back(newType);
2465 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002466}
2467
Jay Foad39c79802011-01-12 09:06:06 +00002468QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002469 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2470
Douglas Gregorec9fd132012-01-14 16:38:05 +00002471 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002472 if (PrevDecl->TypeForDecl)
2473 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2474
John McCall424cec92011-01-19 06:33:43 +00002475 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2476 Decl->TypeForDecl = newType;
2477 Types.push_back(newType);
2478 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002479}
2480
John McCall81904512011-01-06 01:58:22 +00002481QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2482 QualType modifiedType,
2483 QualType equivalentType) {
2484 llvm::FoldingSetNodeID id;
2485 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2486
2487 void *insertPos = 0;
2488 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2489 if (type) return QualType(type, 0);
2490
2491 QualType canon = getCanonicalType(equivalentType);
2492 type = new (*this, TypeAlignment)
2493 AttributedType(canon, attrKind, modifiedType, equivalentType);
2494
2495 Types.push_back(type);
2496 AttributedTypes.InsertNode(type, insertPos);
2497
2498 return QualType(type, 0);
2499}
2500
2501
John McCallcebee162009-10-18 09:09:24 +00002502/// \brief Retrieve a substitution-result type.
2503QualType
2504ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002505 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002506 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002507 && "replacement types must always be canonical");
2508
2509 llvm::FoldingSetNodeID ID;
2510 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2511 void *InsertPos = 0;
2512 SubstTemplateTypeParmType *SubstParm
2513 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2514
2515 if (!SubstParm) {
2516 SubstParm = new (*this, TypeAlignment)
2517 SubstTemplateTypeParmType(Parm, Replacement);
2518 Types.push_back(SubstParm);
2519 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2520 }
2521
2522 return QualType(SubstParm, 0);
2523}
2524
Douglas Gregorada4b792011-01-14 02:55:32 +00002525/// \brief Retrieve a
2526QualType ASTContext::getSubstTemplateTypeParmPackType(
2527 const TemplateTypeParmType *Parm,
2528 const TemplateArgument &ArgPack) {
2529#ifndef NDEBUG
2530 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2531 PEnd = ArgPack.pack_end();
2532 P != PEnd; ++P) {
2533 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2534 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2535 }
2536#endif
2537
2538 llvm::FoldingSetNodeID ID;
2539 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2540 void *InsertPos = 0;
2541 if (SubstTemplateTypeParmPackType *SubstParm
2542 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2543 return QualType(SubstParm, 0);
2544
2545 QualType Canon;
2546 if (!Parm->isCanonicalUnqualified()) {
2547 Canon = getCanonicalType(QualType(Parm, 0));
2548 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2549 ArgPack);
2550 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2551 }
2552
2553 SubstTemplateTypeParmPackType *SubstParm
2554 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2555 ArgPack);
2556 Types.push_back(SubstParm);
2557 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2558 return QualType(SubstParm, 0);
2559}
2560
Douglas Gregoreff93e02009-02-05 23:33:38 +00002561/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002562/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002563/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002564QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002565 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002566 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002567 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002568 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002569 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002570 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002571 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2572
2573 if (TypeParm)
2574 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002575
Chandler Carruth08836322011-05-01 00:51:33 +00002576 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002577 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002578 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002579
2580 TemplateTypeParmType *TypeCheck
2581 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2582 assert(!TypeCheck && "Template type parameter canonical type broken");
2583 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002584 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002585 TypeParm = new (*this, TypeAlignment)
2586 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002587
2588 Types.push_back(TypeParm);
2589 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2590
2591 return QualType(TypeParm, 0);
2592}
2593
John McCalle78aac42010-03-10 03:28:59 +00002594TypeSourceInfo *
2595ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2596 SourceLocation NameLoc,
2597 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002598 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002599 assert(!Name.getAsDependentTemplateName() &&
2600 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002601 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002602
2603 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2604 TemplateSpecializationTypeLoc TL
2605 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002606 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002607 TL.setTemplateNameLoc(NameLoc);
2608 TL.setLAngleLoc(Args.getLAngleLoc());
2609 TL.setRAngleLoc(Args.getRAngleLoc());
2610 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2611 TL.setArgLocInfo(i, Args[i].getLocInfo());
2612 return DI;
2613}
2614
Mike Stump11289f42009-09-09 15:08:12 +00002615QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002616ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002617 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002618 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002619 assert(!Template.getAsDependentTemplateName() &&
2620 "No dependent template names here!");
2621
John McCall6b51f282009-11-23 01:53:49 +00002622 unsigned NumArgs = Args.size();
2623
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002624 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002625 ArgVec.reserve(NumArgs);
2626 for (unsigned i = 0; i != NumArgs; ++i)
2627 ArgVec.push_back(Args[i].getArgument());
2628
John McCall2408e322010-04-27 00:57:59 +00002629 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002630 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002631}
2632
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002633#ifndef NDEBUG
2634static bool hasAnyPackExpansions(const TemplateArgument *Args,
2635 unsigned NumArgs) {
2636 for (unsigned I = 0; I != NumArgs; ++I)
2637 if (Args[I].isPackExpansion())
2638 return true;
2639
2640 return true;
2641}
2642#endif
2643
John McCall0ad16662009-10-29 08:12:44 +00002644QualType
2645ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002646 const TemplateArgument *Args,
2647 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002648 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002649 assert(!Template.getAsDependentTemplateName() &&
2650 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002651 // Look through qualified template names.
2652 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2653 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002654
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002655 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002656 Template.getAsTemplateDecl() &&
2657 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002658 QualType CanonType;
2659 if (!Underlying.isNull())
2660 CanonType = getCanonicalType(Underlying);
2661 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002662 // We can get here with an alias template when the specialization contains
2663 // a pack expansion that does not match up with a parameter pack.
2664 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2665 "Caller must compute aliased type");
2666 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002667 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2668 NumArgs);
2669 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002670
Douglas Gregora8e02e72009-07-28 23:00:59 +00002671 // Allocate the (non-canonical) template specialization type, but don't
2672 // try to unique it: these types typically have location information that
2673 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002674 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2675 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002676 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002677 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002678 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002679 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2680 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002681
Douglas Gregor8bf42052009-02-09 18:46:07 +00002682 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002683 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002684}
2685
Mike Stump11289f42009-09-09 15:08:12 +00002686QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002687ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2688 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002689 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002690 assert(!Template.getAsDependentTemplateName() &&
2691 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002692
Douglas Gregore29139c2011-03-03 17:04:51 +00002693 // Look through qualified template names.
2694 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2695 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002696
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002697 // Build the canonical template specialization type.
2698 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002699 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002700 CanonArgs.reserve(NumArgs);
2701 for (unsigned I = 0; I != NumArgs; ++I)
2702 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2703
2704 // Determine whether this canonical template specialization type already
2705 // exists.
2706 llvm::FoldingSetNodeID ID;
2707 TemplateSpecializationType::Profile(ID, CanonTemplate,
2708 CanonArgs.data(), NumArgs, *this);
2709
2710 void *InsertPos = 0;
2711 TemplateSpecializationType *Spec
2712 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2713
2714 if (!Spec) {
2715 // Allocate a new canonical template specialization type.
2716 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2717 sizeof(TemplateArgument) * NumArgs),
2718 TypeAlignment);
2719 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2720 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002721 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002722 Types.push_back(Spec);
2723 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2724 }
2725
2726 assert(Spec->isDependentType() &&
2727 "Non-dependent template-id type must have a canonical type");
2728 return QualType(Spec, 0);
2729}
2730
2731QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002732ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2733 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002734 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002735 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002736 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002737
2738 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002739 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002740 if (T)
2741 return QualType(T, 0);
2742
Douglas Gregorc42075a2010-02-04 18:10:26 +00002743 QualType Canon = NamedType;
2744 if (!Canon.isCanonical()) {
2745 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002746 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2747 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002748 (void)CheckT;
2749 }
2750
Abramo Bagnara6150c882010-05-11 21:36:43 +00002751 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002752 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002753 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002754 return QualType(T, 0);
2755}
2756
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002757QualType
Jay Foad39c79802011-01-12 09:06:06 +00002758ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002759 llvm::FoldingSetNodeID ID;
2760 ParenType::Profile(ID, InnerType);
2761
2762 void *InsertPos = 0;
2763 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2764 if (T)
2765 return QualType(T, 0);
2766
2767 QualType Canon = InnerType;
2768 if (!Canon.isCanonical()) {
2769 Canon = getCanonicalType(InnerType);
2770 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2771 assert(!CheckT && "Paren canonical type broken");
2772 (void)CheckT;
2773 }
2774
2775 T = new (*this) ParenType(InnerType, Canon);
2776 Types.push_back(T);
2777 ParenTypes.InsertNode(T, InsertPos);
2778 return QualType(T, 0);
2779}
2780
Douglas Gregor02085352010-03-31 20:19:30 +00002781QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2782 NestedNameSpecifier *NNS,
2783 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002784 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002785 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2786
2787 if (Canon.isNull()) {
2788 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002789 ElaboratedTypeKeyword CanonKeyword = Keyword;
2790 if (Keyword == ETK_None)
2791 CanonKeyword = ETK_Typename;
2792
2793 if (CanonNNS != NNS || CanonKeyword != Keyword)
2794 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002795 }
2796
2797 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002798 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002799
2800 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002801 DependentNameType *T
2802 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002803 if (T)
2804 return QualType(T, 0);
2805
Douglas Gregor02085352010-03-31 20:19:30 +00002806 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002807 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002808 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002809 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002810}
2811
Mike Stump11289f42009-09-09 15:08:12 +00002812QualType
John McCallc392f372010-06-11 00:33:02 +00002813ASTContext::getDependentTemplateSpecializationType(
2814 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002815 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002816 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002817 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002818 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002819 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002820 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2821 ArgCopy.push_back(Args[I].getArgument());
2822 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2823 ArgCopy.size(),
2824 ArgCopy.data());
2825}
2826
2827QualType
2828ASTContext::getDependentTemplateSpecializationType(
2829 ElaboratedTypeKeyword Keyword,
2830 NestedNameSpecifier *NNS,
2831 const IdentifierInfo *Name,
2832 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002833 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002834 assert((!NNS || NNS->isDependent()) &&
2835 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002836
Douglas Gregorc42075a2010-02-04 18:10:26 +00002837 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002838 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2839 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002840
2841 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002842 DependentTemplateSpecializationType *T
2843 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002844 if (T)
2845 return QualType(T, 0);
2846
John McCallc392f372010-06-11 00:33:02 +00002847 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002848
John McCallc392f372010-06-11 00:33:02 +00002849 ElaboratedTypeKeyword CanonKeyword = Keyword;
2850 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2851
2852 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002853 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002854 for (unsigned I = 0; I != NumArgs; ++I) {
2855 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2856 if (!CanonArgs[I].structurallyEquals(Args[I]))
2857 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002858 }
2859
John McCallc392f372010-06-11 00:33:02 +00002860 QualType Canon;
2861 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2862 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2863 Name, NumArgs,
2864 CanonArgs.data());
2865
2866 // Find the insert position again.
2867 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2868 }
2869
2870 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2871 sizeof(TemplateArgument) * NumArgs),
2872 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002873 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002874 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002875 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002876 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002877 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002878}
2879
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002880QualType ASTContext::getPackExpansionType(QualType Pattern,
2881 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002882 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002883 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002884
2885 assert(Pattern->containsUnexpandedParameterPack() &&
2886 "Pack expansions must expand one or more parameter packs");
2887 void *InsertPos = 0;
2888 PackExpansionType *T
2889 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2890 if (T)
2891 return QualType(T, 0);
2892
2893 QualType Canon;
2894 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00002895 Canon = getCanonicalType(Pattern);
2896 // The canonical type might not contain an unexpanded parameter pack, if it
2897 // contains an alias template specialization which ignores one of its
2898 // parameters.
2899 if (Canon->containsUnexpandedParameterPack()) {
2900 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002901
Richard Smith68eea502012-07-16 00:20:35 +00002902 // Find the insert position again, in case we inserted an element into
2903 // PackExpansionTypes and invalidated our insert position.
2904 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2905 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00002906 }
2907
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002908 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002909 Types.push_back(T);
2910 PackExpansionTypes.InsertNode(T, InsertPos);
2911 return QualType(T, 0);
2912}
2913
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002914/// CmpProtocolNames - Comparison predicate for sorting protocols
2915/// alphabetically.
2916static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2917 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002918 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002919}
2920
John McCall8b07ec22010-05-15 11:32:37 +00002921static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002922 unsigned NumProtocols) {
2923 if (NumProtocols == 0) return true;
2924
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002925 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2926 return false;
2927
John McCallfc93cf92009-10-22 22:37:11 +00002928 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002929 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2930 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002931 return false;
2932 return true;
2933}
2934
2935static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002936 unsigned &NumProtocols) {
2937 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002938
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002939 // Sort protocols, keyed by name.
2940 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2941
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002942 // Canonicalize.
2943 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2944 Protocols[I] = Protocols[I]->getCanonicalDecl();
2945
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002946 // Remove duplicates.
2947 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2948 NumProtocols = ProtocolsEnd-Protocols;
2949}
2950
John McCall8b07ec22010-05-15 11:32:37 +00002951QualType ASTContext::getObjCObjectType(QualType BaseType,
2952 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002953 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002954 // If the base type is an interface and there aren't any protocols
2955 // to add, then the interface type will do just fine.
2956 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2957 return BaseType;
2958
2959 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002960 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002961 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002962 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002963 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2964 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002965
John McCall8b07ec22010-05-15 11:32:37 +00002966 // Build the canonical type, which has the canonical base type and
2967 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002968 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002969 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2970 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2971 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002972 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002973 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002974 unsigned UniqueCount = NumProtocols;
2975
John McCallfc93cf92009-10-22 22:37:11 +00002976 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002977 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2978 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002979 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002980 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2981 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002982 }
2983
2984 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002985 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2986 }
2987
2988 unsigned Size = sizeof(ObjCObjectTypeImpl);
2989 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2990 void *Mem = Allocate(Size, TypeAlignment);
2991 ObjCObjectTypeImpl *T =
2992 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2993
2994 Types.push_back(T);
2995 ObjCObjectTypes.InsertNode(T, InsertPos);
2996 return QualType(T, 0);
2997}
2998
2999/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3000/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003001QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003002 llvm::FoldingSetNodeID ID;
3003 ObjCObjectPointerType::Profile(ID, ObjectT);
3004
3005 void *InsertPos = 0;
3006 if (ObjCObjectPointerType *QT =
3007 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3008 return QualType(QT, 0);
3009
3010 // Find the canonical object type.
3011 QualType Canonical;
3012 if (!ObjectT.isCanonical()) {
3013 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3014
3015 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003016 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3017 }
3018
Douglas Gregorf85bee62010-02-08 22:59:26 +00003019 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003020 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3021 ObjCObjectPointerType *QType =
3022 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003023
Steve Narofffb4330f2009-06-17 22:40:22 +00003024 Types.push_back(QType);
3025 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003026 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003027}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003028
Douglas Gregor1c283312010-08-11 12:19:30 +00003029/// getObjCInterfaceType - Return the unique reference to the type for the
3030/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003031QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3032 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003033 if (Decl->TypeForDecl)
3034 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003035
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003036 if (PrevDecl) {
3037 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3038 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3039 return QualType(PrevDecl->TypeForDecl, 0);
3040 }
3041
Douglas Gregor7671e532011-12-16 16:34:57 +00003042 // Prefer the definition, if there is one.
3043 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3044 Decl = Def;
3045
Douglas Gregor1c283312010-08-11 12:19:30 +00003046 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3047 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3048 Decl->TypeForDecl = T;
3049 Types.push_back(T);
3050 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003051}
3052
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003053/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3054/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003055/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003056/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003057/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003058QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003059 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003060 if (tofExpr->isTypeDependent()) {
3061 llvm::FoldingSetNodeID ID;
3062 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003063
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003064 void *InsertPos = 0;
3065 DependentTypeOfExprType *Canon
3066 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3067 if (Canon) {
3068 // We already have a "canonical" version of an identical, dependent
3069 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003070 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003071 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003072 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003073 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003074 Canon
3075 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003076 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3077 toe = Canon;
3078 }
3079 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003080 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003081 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003082 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003083 Types.push_back(toe);
3084 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003085}
3086
Steve Naroffa773cd52007-08-01 18:02:17 +00003087/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3088/// TypeOfType AST's. The only motivation to unique these nodes would be
3089/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003090/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003091/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003092QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003093 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003094 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003095 Types.push_back(tot);
3096 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003097}
3098
Anders Carlssonad6bd352009-06-24 21:24:56 +00003099
Anders Carlsson81df7b82009-06-24 19:06:50 +00003100/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3101/// DecltypeType AST's. The only motivation to unique these nodes would be
3102/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003103/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003104/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003105QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003106 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003107
3108 // C++0x [temp.type]p2:
3109 // If an expression e involves a template parameter, decltype(e) denotes a
3110 // unique dependent type. Two such decltype-specifiers refer to the same
3111 // type only if their expressions are equivalent (14.5.6.1).
3112 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003113 llvm::FoldingSetNodeID ID;
3114 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003115
Douglas Gregora21f6c32009-07-30 23:36:40 +00003116 void *InsertPos = 0;
3117 DependentDecltypeType *Canon
3118 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3119 if (Canon) {
3120 // We already have a "canonical" version of an equivalent, dependent
3121 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003122 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003123 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003124 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003125 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003126 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003127 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3128 dt = Canon;
3129 }
3130 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003131 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3132 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003133 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003134 Types.push_back(dt);
3135 return QualType(dt, 0);
3136}
3137
Alexis Hunte852b102011-05-24 22:41:36 +00003138/// getUnaryTransformationType - We don't unique these, since the memory
3139/// savings are minimal and these are rare.
3140QualType ASTContext::getUnaryTransformType(QualType BaseType,
3141 QualType UnderlyingType,
3142 UnaryTransformType::UTTKind Kind)
3143 const {
3144 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003145 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3146 Kind,
3147 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003148 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003149 Types.push_back(Ty);
3150 return QualType(Ty, 0);
3151}
3152
Richard Smithb2bc2e62011-02-21 20:05:19 +00003153/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003154QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003155 void *InsertPos = 0;
3156 if (!DeducedType.isNull()) {
3157 // Look in the folding set for an existing type.
3158 llvm::FoldingSetNodeID ID;
3159 AutoType::Profile(ID, DeducedType);
3160 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3161 return QualType(AT, 0);
3162 }
3163
3164 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3165 Types.push_back(AT);
3166 if (InsertPos)
3167 AutoTypes.InsertNode(AT, InsertPos);
3168 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003169}
3170
Eli Friedman0dfb8892011-10-06 23:00:33 +00003171/// getAtomicType - Return the uniqued reference to the atomic type for
3172/// the given value type.
3173QualType ASTContext::getAtomicType(QualType T) const {
3174 // Unique pointers, to guarantee there is only one pointer of a particular
3175 // structure.
3176 llvm::FoldingSetNodeID ID;
3177 AtomicType::Profile(ID, T);
3178
3179 void *InsertPos = 0;
3180 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3181 return QualType(AT, 0);
3182
3183 // If the atomic value type isn't canonical, this won't be a canonical type
3184 // either, so fill in the canonical type field.
3185 QualType Canonical;
3186 if (!T.isCanonical()) {
3187 Canonical = getAtomicType(getCanonicalType(T));
3188
3189 // Get the new insert position for the node we care about.
3190 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3191 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3192 }
3193 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3194 Types.push_back(New);
3195 AtomicTypes.InsertNode(New, InsertPos);
3196 return QualType(New, 0);
3197}
3198
Richard Smith02e85f32011-04-14 22:09:26 +00003199/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3200QualType ASTContext::getAutoDeductType() const {
3201 if (AutoDeductTy.isNull())
3202 AutoDeductTy = getAutoType(QualType());
3203 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3204 return AutoDeductTy;
3205}
3206
3207/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3208QualType ASTContext::getAutoRRefDeductType() const {
3209 if (AutoRRefDeductTy.isNull())
3210 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3211 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3212 return AutoRRefDeductTy;
3213}
3214
Chris Lattnerfb072462007-01-23 05:45:31 +00003215/// getTagDeclType - Return the unique reference to the type for the
3216/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003217QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003218 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003219 // FIXME: What is the design on getTagDeclType when it requires casting
3220 // away const? mutable?
3221 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003222}
3223
Mike Stump11289f42009-09-09 15:08:12 +00003224/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3225/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3226/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003227CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003228 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003229}
Chris Lattnerfb072462007-01-23 05:45:31 +00003230
Hans Wennborg27541db2011-10-27 08:29:09 +00003231/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3232CanQualType ASTContext::getIntMaxType() const {
3233 return getFromTargetType(Target->getIntMaxType());
3234}
3235
3236/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3237CanQualType ASTContext::getUIntMaxType() const {
3238 return getFromTargetType(Target->getUIntMaxType());
3239}
3240
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003241/// getSignedWCharType - Return the type of "signed wchar_t".
3242/// Used when in C++, as a GCC extension.
3243QualType ASTContext::getSignedWCharType() const {
3244 // FIXME: derive from "Target" ?
3245 return WCharTy;
3246}
3247
3248/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3249/// Used when in C++, as a GCC extension.
3250QualType ASTContext::getUnsignedWCharType() const {
3251 // FIXME: derive from "Target" ?
3252 return UnsignedIntTy;
3253}
3254
Hans Wennborg27541db2011-10-27 08:29:09 +00003255/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003256/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3257QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003258 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003259}
3260
Chris Lattnera21ad802008-04-02 05:18:44 +00003261//===----------------------------------------------------------------------===//
3262// Type Operators
3263//===----------------------------------------------------------------------===//
3264
Jay Foad39c79802011-01-12 09:06:06 +00003265CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003266 // Push qualifiers into arrays, and then discard any remaining
3267 // qualifiers.
3268 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003269 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003270 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003271 QualType Result;
3272 if (isa<ArrayType>(Ty)) {
3273 Result = getArrayDecayedType(QualType(Ty,0));
3274 } else if (isa<FunctionType>(Ty)) {
3275 Result = getPointerType(QualType(Ty, 0));
3276 } else {
3277 Result = QualType(Ty, 0);
3278 }
3279
3280 return CanQualType::CreateUnsafe(Result);
3281}
3282
John McCall6c9dd522011-01-18 07:41:22 +00003283QualType ASTContext::getUnqualifiedArrayType(QualType type,
3284 Qualifiers &quals) {
3285 SplitQualType splitType = type.getSplitUnqualifiedType();
3286
3287 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3288 // the unqualified desugared type and then drops it on the floor.
3289 // We then have to strip that sugar back off with
3290 // getUnqualifiedDesugaredType(), which is silly.
3291 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003292 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003293
3294 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003295 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003296 quals = splitType.Quals;
3297 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003298 }
3299
John McCall6c9dd522011-01-18 07:41:22 +00003300 // Otherwise, recurse on the array's element type.
3301 QualType elementType = AT->getElementType();
3302 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3303
3304 // If that didn't change the element type, AT has no qualifiers, so we
3305 // can just use the results in splitType.
3306 if (elementType == unqualElementType) {
3307 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003308 quals = splitType.Quals;
3309 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003310 }
3311
3312 // Otherwise, add in the qualifiers from the outermost type, then
3313 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003314 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003315
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003316 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003317 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003318 CAT->getSizeModifier(), 0);
3319 }
3320
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003321 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003322 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003323 }
3324
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003325 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003326 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003327 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003328 VAT->getSizeModifier(),
3329 VAT->getIndexTypeCVRQualifiers(),
3330 VAT->getBracketsRange());
3331 }
3332
3333 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003334 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003335 DSAT->getSizeModifier(), 0,
3336 SourceRange());
3337}
3338
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003339/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3340/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3341/// they point to and return true. If T1 and T2 aren't pointer types
3342/// or pointer-to-member types, or if they are not similar at this
3343/// level, returns false and leaves T1 and T2 unchanged. Top-level
3344/// qualifiers on T1 and T2 are ignored. This function will typically
3345/// be called in a loop that successively "unwraps" pointer and
3346/// pointer-to-member types to compare them at each level.
3347bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3348 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3349 *T2PtrType = T2->getAs<PointerType>();
3350 if (T1PtrType && T2PtrType) {
3351 T1 = T1PtrType->getPointeeType();
3352 T2 = T2PtrType->getPointeeType();
3353 return true;
3354 }
3355
3356 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3357 *T2MPType = T2->getAs<MemberPointerType>();
3358 if (T1MPType && T2MPType &&
3359 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3360 QualType(T2MPType->getClass(), 0))) {
3361 T1 = T1MPType->getPointeeType();
3362 T2 = T2MPType->getPointeeType();
3363 return true;
3364 }
3365
David Blaikiebbafb8a2012-03-11 07:00:24 +00003366 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003367 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3368 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3369 if (T1OPType && T2OPType) {
3370 T1 = T1OPType->getPointeeType();
3371 T2 = T2OPType->getPointeeType();
3372 return true;
3373 }
3374 }
3375
3376 // FIXME: Block pointers, too?
3377
3378 return false;
3379}
3380
Jay Foad39c79802011-01-12 09:06:06 +00003381DeclarationNameInfo
3382ASTContext::getNameForTemplate(TemplateName Name,
3383 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003384 switch (Name.getKind()) {
3385 case TemplateName::QualifiedTemplate:
3386 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003387 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003388 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3389 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003390
John McCalld9dfe3a2011-06-30 08:33:18 +00003391 case TemplateName::OverloadedTemplate: {
3392 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3393 // DNInfo work in progress: CHECKME: what about DNLoc?
3394 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3395 }
3396
3397 case TemplateName::DependentTemplate: {
3398 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003399 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003400 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003401 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3402 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003403 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003404 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3405 // DNInfo work in progress: FIXME: source locations?
3406 DeclarationNameLoc DNLoc;
3407 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3408 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3409 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003410 }
3411 }
3412
John McCalld9dfe3a2011-06-30 08:33:18 +00003413 case TemplateName::SubstTemplateTemplateParm: {
3414 SubstTemplateTemplateParmStorage *subst
3415 = Name.getAsSubstTemplateTemplateParm();
3416 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3417 NameLoc);
3418 }
3419
3420 case TemplateName::SubstTemplateTemplateParmPack: {
3421 SubstTemplateTemplateParmPackStorage *subst
3422 = Name.getAsSubstTemplateTemplateParmPack();
3423 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3424 NameLoc);
3425 }
3426 }
3427
3428 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003429}
3430
Jay Foad39c79802011-01-12 09:06:06 +00003431TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003432 switch (Name.getKind()) {
3433 case TemplateName::QualifiedTemplate:
3434 case TemplateName::Template: {
3435 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003436 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003437 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003438 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3439
3440 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003441 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003442 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003443
John McCalld9dfe3a2011-06-30 08:33:18 +00003444 case TemplateName::OverloadedTemplate:
3445 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003446
John McCalld9dfe3a2011-06-30 08:33:18 +00003447 case TemplateName::DependentTemplate: {
3448 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3449 assert(DTN && "Non-dependent template names must refer to template decls.");
3450 return DTN->CanonicalTemplateName;
3451 }
3452
3453 case TemplateName::SubstTemplateTemplateParm: {
3454 SubstTemplateTemplateParmStorage *subst
3455 = Name.getAsSubstTemplateTemplateParm();
3456 return getCanonicalTemplateName(subst->getReplacement());
3457 }
3458
3459 case TemplateName::SubstTemplateTemplateParmPack: {
3460 SubstTemplateTemplateParmPackStorage *subst
3461 = Name.getAsSubstTemplateTemplateParmPack();
3462 TemplateTemplateParmDecl *canonParameter
3463 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3464 TemplateArgument canonArgPack
3465 = getCanonicalTemplateArgument(subst->getArgumentPack());
3466 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3467 }
3468 }
3469
3470 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003471}
3472
Douglas Gregoradee3e32009-11-11 23:06:43 +00003473bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3474 X = getCanonicalTemplateName(X);
3475 Y = getCanonicalTemplateName(Y);
3476 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3477}
3478
Mike Stump11289f42009-09-09 15:08:12 +00003479TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003480ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003481 switch (Arg.getKind()) {
3482 case TemplateArgument::Null:
3483 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregora8e02e72009-07-28 23:00:59 +00003485 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003486 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003487
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003488 case TemplateArgument::Declaration: {
3489 if (Decl *D = Arg.getAsDecl())
3490 return TemplateArgument(D->getCanonicalDecl());
3491 return TemplateArgument((Decl*)0);
3492 }
Mike Stump11289f42009-09-09 15:08:12 +00003493
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003494 case TemplateArgument::Template:
3495 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003496
3497 case TemplateArgument::TemplateExpansion:
3498 return TemplateArgument(getCanonicalTemplateName(
3499 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003500 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003501
Douglas Gregora8e02e72009-07-28 23:00:59 +00003502 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003503 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003504
Douglas Gregora8e02e72009-07-28 23:00:59 +00003505 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003506 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003507
Douglas Gregora8e02e72009-07-28 23:00:59 +00003508 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003509 if (Arg.pack_size() == 0)
3510 return Arg;
3511
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003512 TemplateArgument *CanonArgs
3513 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003514 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003515 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003516 AEnd = Arg.pack_end();
3517 A != AEnd; (void)++A, ++Idx)
3518 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003519
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003520 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003521 }
3522 }
3523
3524 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003525 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003526}
3527
Douglas Gregor333489b2009-03-27 23:10:48 +00003528NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003529ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003530 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003531 return 0;
3532
3533 switch (NNS->getKind()) {
3534 case NestedNameSpecifier::Identifier:
3535 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003536 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003537 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3538 NNS->getAsIdentifier());
3539
3540 case NestedNameSpecifier::Namespace:
3541 // A namespace is canonical; build a nested-name-specifier with
3542 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003543 return NestedNameSpecifier::Create(*this, 0,
3544 NNS->getAsNamespace()->getOriginalNamespace());
3545
3546 case NestedNameSpecifier::NamespaceAlias:
3547 // A namespace is canonical; build a nested-name-specifier with
3548 // this namespace and no prefix.
3549 return NestedNameSpecifier::Create(*this, 0,
3550 NNS->getAsNamespaceAlias()->getNamespace()
3551 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003552
3553 case NestedNameSpecifier::TypeSpec:
3554 case NestedNameSpecifier::TypeSpecWithTemplate: {
3555 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003556
3557 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3558 // break it apart into its prefix and identifier, then reconsititute those
3559 // as the canonical nested-name-specifier. This is required to canonicalize
3560 // a dependent nested-name-specifier involving typedefs of dependent-name
3561 // types, e.g.,
3562 // typedef typename T::type T1;
3563 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003564 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3565 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003566 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003567
Eli Friedman5358a0a2012-03-03 04:09:56 +00003568 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3569 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3570 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003571 return NestedNameSpecifier::Create(*this, 0, false,
3572 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003573 }
3574
3575 case NestedNameSpecifier::Global:
3576 // The global specifier is canonical and unique.
3577 return NNS;
3578 }
3579
David Blaikie8a40f702012-01-17 06:56:22 +00003580 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003581}
3582
Chris Lattner7adf0762008-08-04 07:31:14 +00003583
Jay Foad39c79802011-01-12 09:06:06 +00003584const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003585 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003586 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003587 // Handle the common positive case fast.
3588 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3589 return AT;
3590 }
Mike Stump11289f42009-09-09 15:08:12 +00003591
John McCall8ccfcb52009-09-24 19:53:00 +00003592 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003593 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003594 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003595
John McCall8ccfcb52009-09-24 19:53:00 +00003596 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003597 // implements C99 6.7.3p8: "If the specification of an array type includes
3598 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003599
Chris Lattner7adf0762008-08-04 07:31:14 +00003600 // If we get here, we either have type qualifiers on the type, or we have
3601 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003602 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003603
John McCall33ddac02011-01-19 10:06:00 +00003604 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003605 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003606
Chris Lattner7adf0762008-08-04 07:31:14 +00003607 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003608 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003609 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003610 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003611
Chris Lattner7adf0762008-08-04 07:31:14 +00003612 // Otherwise, we have an array and we have qualifiers on it. Push the
3613 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003614 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003615
Chris Lattner7adf0762008-08-04 07:31:14 +00003616 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3617 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3618 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003619 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003620 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3621 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3622 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003623 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003624
Mike Stump11289f42009-09-09 15:08:12 +00003625 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003626 = dyn_cast<DependentSizedArrayType>(ATy))
3627 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003628 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003629 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003630 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003631 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003632 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003633
Chris Lattner7adf0762008-08-04 07:31:14 +00003634 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003635 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003636 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003637 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003638 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003639 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003640}
3641
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003642QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003643 // C99 6.7.5.3p7:
3644 // A declaration of a parameter as "array of type" shall be
3645 // adjusted to "qualified pointer to type", where the type
3646 // qualifiers (if any) are those specified within the [ and ] of
3647 // the array type derivation.
3648 if (T->isArrayType())
3649 return getArrayDecayedType(T);
3650
3651 // C99 6.7.5.3p8:
3652 // A declaration of a parameter as "function returning type"
3653 // shall be adjusted to "pointer to function returning type", as
3654 // in 6.3.2.1.
3655 if (T->isFunctionType())
3656 return getPointerType(T);
3657
3658 return T;
3659}
3660
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003661QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003662 T = getVariableArrayDecayedType(T);
3663 T = getAdjustedParameterType(T);
3664 return T.getUnqualifiedType();
3665}
3666
Chris Lattnera21ad802008-04-02 05:18:44 +00003667/// getArrayDecayedType - Return the properly qualified result of decaying the
3668/// specified array type to a pointer. This operation is non-trivial when
3669/// handling typedefs etc. The canonical type of "T" must be an array type,
3670/// this returns a pointer to a properly qualified element of the array.
3671///
3672/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003673QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003674 // Get the element type with 'getAsArrayType' so that we don't lose any
3675 // typedefs in the element type of the array. This also handles propagation
3676 // of type qualifiers from the array type into the element type if present
3677 // (C99 6.7.3p8).
3678 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3679 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003680
Chris Lattner7adf0762008-08-04 07:31:14 +00003681 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003682
3683 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003684 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003685}
3686
John McCall33ddac02011-01-19 10:06:00 +00003687QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3688 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003689}
3690
John McCall33ddac02011-01-19 10:06:00 +00003691QualType ASTContext::getBaseElementType(QualType type) const {
3692 Qualifiers qs;
3693 while (true) {
3694 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003695 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003696 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003697
John McCall33ddac02011-01-19 10:06:00 +00003698 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003699 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
John McCall33ddac02011-01-19 10:06:00 +00003702 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003703}
3704
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003705/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003706uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003707ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3708 uint64_t ElementCount = 1;
3709 do {
3710 ElementCount *= CA->getSize().getZExtValue();
3711 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3712 } while (CA);
3713 return ElementCount;
3714}
3715
Steve Naroff0af91202007-04-27 21:51:21 +00003716/// getFloatingRank - Return a relative rank for floating point types.
3717/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003718static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003719 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003720 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003721
John McCall9dd450b2009-09-21 23:43:11 +00003722 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3723 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003724 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003725 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003726 case BuiltinType::Float: return FloatRank;
3727 case BuiltinType::Double: return DoubleRank;
3728 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003729 }
3730}
3731
Mike Stump11289f42009-09-09 15:08:12 +00003732/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3733/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003734/// 'typeDomain' is a real floating point or complex type.
3735/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003736QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3737 QualType Domain) const {
3738 FloatingRank EltRank = getFloatingRank(Size);
3739 if (Domain->isComplexType()) {
3740 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003741 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003742 case FloatRank: return FloatComplexTy;
3743 case DoubleRank: return DoubleComplexTy;
3744 case LongDoubleRank: return LongDoubleComplexTy;
3745 }
Steve Naroff0af91202007-04-27 21:51:21 +00003746 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003747
3748 assert(Domain->isRealFloatingType() && "Unknown domain!");
3749 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003750 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003751 case FloatRank: return FloatTy;
3752 case DoubleRank: return DoubleTy;
3753 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003754 }
David Blaikief47fa302012-01-17 02:30:50 +00003755 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003756}
3757
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003758/// getFloatingTypeOrder - Compare the rank of the two specified floating
3759/// point types, ignoring the domain of the type (i.e. 'double' ==
3760/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003761/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003762int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003763 FloatingRank LHSR = getFloatingRank(LHS);
3764 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003765
Chris Lattnerb90739d2008-04-06 23:38:49 +00003766 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003767 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003768 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003769 return 1;
3770 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003771}
3772
Chris Lattner76a00cf2008-04-06 22:59:24 +00003773/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3774/// routine will assert if passed a built-in type that isn't an integer or enum,
3775/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003776unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003777 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003778
Chris Lattner76a00cf2008-04-06 22:59:24 +00003779 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003780 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003781 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003782 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003783 case BuiltinType::Char_S:
3784 case BuiltinType::Char_U:
3785 case BuiltinType::SChar:
3786 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003787 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003788 case BuiltinType::Short:
3789 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003790 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003791 case BuiltinType::Int:
3792 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003793 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003794 case BuiltinType::Long:
3795 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003796 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003797 case BuiltinType::LongLong:
3798 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003799 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003800 case BuiltinType::Int128:
3801 case BuiltinType::UInt128:
3802 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003803 }
3804}
3805
Eli Friedman629ffb92009-08-20 04:21:42 +00003806/// \brief Whether this is a promotable bitfield reference according
3807/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3808///
3809/// \returns the type this bit-field will promote to, or NULL if no
3810/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003811QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003812 if (E->isTypeDependent() || E->isValueDependent())
3813 return QualType();
3814
Eli Friedman629ffb92009-08-20 04:21:42 +00003815 FieldDecl *Field = E->getBitField();
3816 if (!Field)
3817 return QualType();
3818
3819 QualType FT = Field->getType();
3820
Richard Smithcaf33902011-10-10 18:28:20 +00003821 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003822 uint64_t IntSize = getTypeSize(IntTy);
3823 // GCC extension compatibility: if the bit-field size is less than or equal
3824 // to the size of int, it gets promoted no matter what its type is.
3825 // For instance, unsigned long bf : 4 gets promoted to signed int.
3826 if (BitWidth < IntSize)
3827 return IntTy;
3828
3829 if (BitWidth == IntSize)
3830 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3831
3832 // Types bigger than int are not subject to promotions, and therefore act
3833 // like the base type.
3834 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3835 // is ridiculous.
3836 return QualType();
3837}
3838
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003839/// getPromotedIntegerType - Returns the type that Promotable will
3840/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3841/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003842QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003843 assert(!Promotable.isNull());
3844 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003845 if (const EnumType *ET = Promotable->getAs<EnumType>())
3846 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003847
3848 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3849 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3850 // (3.9.1) can be converted to a prvalue of the first of the following
3851 // types that can represent all the values of its underlying type:
3852 // int, unsigned int, long int, unsigned long int, long long int, or
3853 // unsigned long long int [...]
3854 // FIXME: Is there some better way to compute this?
3855 if (BT->getKind() == BuiltinType::WChar_S ||
3856 BT->getKind() == BuiltinType::WChar_U ||
3857 BT->getKind() == BuiltinType::Char16 ||
3858 BT->getKind() == BuiltinType::Char32) {
3859 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3860 uint64_t FromSize = getTypeSize(BT);
3861 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3862 LongLongTy, UnsignedLongLongTy };
3863 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3864 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3865 if (FromSize < ToSize ||
3866 (FromSize == ToSize &&
3867 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3868 return PromoteTypes[Idx];
3869 }
3870 llvm_unreachable("char type should fit into long long");
3871 }
3872 }
3873
3874 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003875 if (Promotable->isSignedIntegerType())
3876 return IntTy;
3877 uint64_t PromotableSize = getTypeSize(Promotable);
3878 uint64_t IntSize = getTypeSize(IntTy);
3879 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3880 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3881}
3882
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003883/// \brief Recurses in pointer/array types until it finds an objc retainable
3884/// type and returns its ownership.
3885Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3886 while (!T.isNull()) {
3887 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3888 return T.getObjCLifetime();
3889 if (T->isArrayType())
3890 T = getBaseElementType(T);
3891 else if (const PointerType *PT = T->getAs<PointerType>())
3892 T = PT->getPointeeType();
3893 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003894 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003895 else
3896 break;
3897 }
3898
3899 return Qualifiers::OCL_None;
3900}
3901
Mike Stump11289f42009-09-09 15:08:12 +00003902/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003903/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003904/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003905int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003906 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3907 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003908 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003909
Chris Lattner76a00cf2008-04-06 22:59:24 +00003910 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3911 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003912
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003913 unsigned LHSRank = getIntegerRank(LHSC);
3914 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003915
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003916 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3917 if (LHSRank == RHSRank) return 0;
3918 return LHSRank > RHSRank ? 1 : -1;
3919 }
Mike Stump11289f42009-09-09 15:08:12 +00003920
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003921 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3922 if (LHSUnsigned) {
3923 // If the unsigned [LHS] type is larger, return it.
3924 if (LHSRank >= RHSRank)
3925 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003926
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003927 // If the signed type can represent all values of the unsigned type, it
3928 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003929 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003930 return -1;
3931 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003932
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003933 // If the unsigned [RHS] type is larger, return it.
3934 if (RHSRank >= LHSRank)
3935 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003936
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003937 // If the signed type can represent all values of the unsigned type, it
3938 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003939 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003940 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003941}
Anders Carlsson98f07902007-08-17 05:31:46 +00003942
Anders Carlsson6d417272009-11-14 21:45:58 +00003943static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003944CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3945 DeclContext *DC, IdentifierInfo *Id) {
3946 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003947 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003948 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003949 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003950 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003951}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003952
Mike Stump11289f42009-09-09 15:08:12 +00003953// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003954QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003955 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003956 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003957 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003958 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003959 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003960
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003961 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003962
Anders Carlsson98f07902007-08-17 05:31:46 +00003963 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003964 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003965 // int flags;
3966 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003967 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003968 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003969 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003970 FieldTypes[3] = LongTy;
3971
Anders Carlsson98f07902007-08-17 05:31:46 +00003972 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003973 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003974 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003975 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003976 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003977 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003978 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003979 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003980 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003981 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003982 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003983 }
3984
Douglas Gregord5058122010-02-11 01:19:42 +00003985 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003986 }
Mike Stump11289f42009-09-09 15:08:12 +00003987
Anders Carlsson98f07902007-08-17 05:31:46 +00003988 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003989}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003990
Douglas Gregor512b0772009-04-23 22:29:11 +00003991void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003992 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003993 assert(Rec && "Invalid CFConstantStringType");
3994 CFConstantStringTypeDecl = Rec->getDecl();
3995}
3996
Jay Foad39c79802011-01-12 09:06:06 +00003997QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003998 if (BlockDescriptorType)
3999 return getTagDeclType(BlockDescriptorType);
4000
4001 RecordDecl *T;
4002 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004003 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004004 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004005 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004006
4007 QualType FieldTypes[] = {
4008 UnsignedLongTy,
4009 UnsignedLongTy,
4010 };
4011
4012 const char *FieldNames[] = {
4013 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004014 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004015 };
4016
4017 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004018 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004019 SourceLocation(),
4020 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004021 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004022 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004023 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004024 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004025 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004026 T->addDecl(Field);
4027 }
4028
Douglas Gregord5058122010-02-11 01:19:42 +00004029 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004030
4031 BlockDescriptorType = T;
4032
4033 return getTagDeclType(BlockDescriptorType);
4034}
4035
Jay Foad39c79802011-01-12 09:06:06 +00004036QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004037 if (BlockDescriptorExtendedType)
4038 return getTagDeclType(BlockDescriptorExtendedType);
4039
4040 RecordDecl *T;
4041 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004042 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004043 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004044 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004045
4046 QualType FieldTypes[] = {
4047 UnsignedLongTy,
4048 UnsignedLongTy,
4049 getPointerType(VoidPtrTy),
4050 getPointerType(VoidPtrTy)
4051 };
4052
4053 const char *FieldNames[] = {
4054 "reserved",
4055 "Size",
4056 "CopyFuncPtr",
4057 "DestroyFuncPtr"
4058 };
4059
4060 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004061 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004062 SourceLocation(),
4063 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004064 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004065 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004066 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004067 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004068 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004069 T->addDecl(Field);
4070 }
4071
Douglas Gregord5058122010-02-11 01:19:42 +00004072 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004073
4074 BlockDescriptorExtendedType = T;
4075
4076 return getTagDeclType(BlockDescriptorExtendedType);
4077}
4078
Jay Foad39c79802011-01-12 09:06:06 +00004079bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004080 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004081 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004082 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004083 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4084 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004085 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004086
4087 }
4088 }
Mike Stump94967902009-10-21 18:16:27 +00004089 return false;
4090}
4091
Jay Foad39c79802011-01-12 09:06:06 +00004092QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004093ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004094 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004095 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004096 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004097 // unsigned int __flags;
4098 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004099 // void *__copy_helper; // as needed
4100 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004101 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004102 // } *
4103
Mike Stump94967902009-10-21 18:16:27 +00004104 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4105
4106 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004107 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004108 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4109 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004110 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004111 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004112 T->startDefinition();
4113 QualType Int32Ty = IntTy;
4114 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4115 QualType FieldTypes[] = {
4116 getPointerType(VoidPtrTy),
4117 getPointerType(getTagDeclType(T)),
4118 Int32Ty,
4119 Int32Ty,
4120 getPointerType(VoidPtrTy),
4121 getPointerType(VoidPtrTy),
4122 Ty
4123 };
4124
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004125 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004126 "__isa",
4127 "__forwarding",
4128 "__flags",
4129 "__size",
4130 "__copy_helper",
4131 "__destroy_helper",
4132 DeclName,
4133 };
4134
4135 for (size_t i = 0; i < 7; ++i) {
4136 if (!HasCopyAndDispose && i >=4 && i <= 5)
4137 continue;
4138 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004139 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004140 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004141 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004142 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004143 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004144 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004145 T->addDecl(Field);
4146 }
4147
Douglas Gregord5058122010-02-11 01:19:42 +00004148 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004149
4150 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004151}
4152
Douglas Gregorbab8a962011-09-08 01:46:34 +00004153TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4154 if (!ObjCInstanceTypeDecl)
4155 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4156 getTranslationUnitDecl(),
4157 SourceLocation(),
4158 SourceLocation(),
4159 &Idents.get("instancetype"),
4160 getTrivialTypeSourceInfo(getObjCIdType()));
4161 return ObjCInstanceTypeDecl;
4162}
4163
Anders Carlsson18acd442007-10-29 06:33:42 +00004164// This returns true if a type has been typedefed to BOOL:
4165// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004166static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004167 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004168 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4169 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004170
Anders Carlssond8499822007-10-29 05:01:08 +00004171 return false;
4172}
4173
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004174/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004175/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004176CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004177 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4178 return CharUnits::Zero();
4179
Ken Dyck40775002010-01-11 17:06:35 +00004180 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004181
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004182 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004183 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004184 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004185 // Treat arrays as pointers, since that's how they're passed in.
4186 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004187 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004188 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004189}
4190
4191static inline
4192std::string charUnitsToString(const CharUnits &CU) {
4193 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004194}
4195
John McCall351762c2011-02-07 10:33:21 +00004196/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004197/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004198std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4199 std::string S;
4200
David Chisnall950a9512009-11-17 19:33:30 +00004201 const BlockDecl *Decl = Expr->getBlockDecl();
4202 QualType BlockTy =
4203 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4204 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004205 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004206 // Compute size of all parameters.
4207 // Start with computing size of a pointer in number of bytes.
4208 // FIXME: There might(should) be a better way of doing this computation!
4209 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004210 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4211 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004212 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004213 E = Decl->param_end(); PI != E; ++PI) {
4214 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004215 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004216 if (sz.isZero())
4217 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004218 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004219 ParmOffset += sz;
4220 }
4221 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004222 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004223 // Block pointer and offset.
4224 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004225
4226 // Argument types.
4227 ParmOffset = PtrSize;
4228 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4229 Decl->param_end(); PI != E; ++PI) {
4230 ParmVarDecl *PVDecl = *PI;
4231 QualType PType = PVDecl->getOriginalType();
4232 if (const ArrayType *AT =
4233 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4234 // Use array's original type only if it has known number of
4235 // elements.
4236 if (!isa<ConstantArrayType>(AT))
4237 PType = PVDecl->getType();
4238 } else if (PType->isFunctionType())
4239 PType = PVDecl->getType();
4240 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004241 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004242 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004243 }
John McCall351762c2011-02-07 10:33:21 +00004244
4245 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004246}
4247
Douglas Gregora9d84932011-05-27 01:19:52 +00004248bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004249 std::string& S) {
4250 // Encode result type.
4251 getObjCEncodingForType(Decl->getResultType(), S);
4252 CharUnits ParmOffset;
4253 // Compute size of all parameters.
4254 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4255 E = Decl->param_end(); PI != E; ++PI) {
4256 QualType PType = (*PI)->getType();
4257 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004258 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004259 continue;
4260
David Chisnall50e4eba2010-12-30 14:05:53 +00004261 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004262 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004263 ParmOffset += sz;
4264 }
4265 S += charUnitsToString(ParmOffset);
4266 ParmOffset = CharUnits::Zero();
4267
4268 // Argument types.
4269 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4270 E = Decl->param_end(); PI != E; ++PI) {
4271 ParmVarDecl *PVDecl = *PI;
4272 QualType PType = PVDecl->getOriginalType();
4273 if (const ArrayType *AT =
4274 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4275 // Use array's original type only if it has known number of
4276 // elements.
4277 if (!isa<ConstantArrayType>(AT))
4278 PType = PVDecl->getType();
4279 } else if (PType->isFunctionType())
4280 PType = PVDecl->getType();
4281 getObjCEncodingForType(PType, S);
4282 S += charUnitsToString(ParmOffset);
4283 ParmOffset += getObjCEncodingTypeSize(PType);
4284 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004285
4286 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004287}
4288
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004289/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4290/// method parameter or return type. If Extended, include class names and
4291/// block object types.
4292void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4293 QualType T, std::string& S,
4294 bool Extended) const {
4295 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4296 getObjCEncodingForTypeQualifier(QT, S);
4297 // Encode parameter type.
4298 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4299 true /*OutermostType*/,
4300 false /*EncodingProperty*/,
4301 false /*StructField*/,
4302 Extended /*EncodeBlockParameters*/,
4303 Extended /*EncodeClassNames*/);
4304}
4305
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004306/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004307/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004308bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004309 std::string& S,
4310 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004311 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004312 // Encode return type.
4313 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4314 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004315 // Compute size of all parameters.
4316 // Start with computing size of a pointer in number of bytes.
4317 // FIXME: There might(should) be a better way of doing this computation!
4318 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004319 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004320 // The first two arguments (self and _cmd) are pointers; account for
4321 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004322 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004323 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004324 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004325 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004326 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004327 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004328 continue;
4329
Ken Dyck40775002010-01-11 17:06:35 +00004330 assert (sz.isPositive() &&
4331 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004332 ParmOffset += sz;
4333 }
Ken Dyck40775002010-01-11 17:06:35 +00004334 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004335 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004336 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004337
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004338 // Argument types.
4339 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004340 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004341 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004342 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004343 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004344 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004345 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4346 // Use array's original type only if it has known number of
4347 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004348 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004349 PType = PVDecl->getType();
4350 } else if (PType->isFunctionType())
4351 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004352 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4353 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004354 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004355 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004356 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004357
4358 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004359}
4360
Daniel Dunbar4932b362008-08-28 04:38:10 +00004361/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004362/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004363/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4364/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004365/// Property attributes are stored as a comma-delimited C string. The simple
4366/// attributes readonly and bycopy are encoded as single characters. The
4367/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4368/// encoded as single characters, followed by an identifier. Property types
4369/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004370/// these attributes are defined by the following enumeration:
4371/// @code
4372/// enum PropertyAttributes {
4373/// kPropertyReadOnly = 'R', // property is read-only.
4374/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4375/// kPropertyByref = '&', // property is a reference to the value last assigned
4376/// kPropertyDynamic = 'D', // property is dynamic
4377/// kPropertyGetter = 'G', // followed by getter selector name
4378/// kPropertySetter = 'S', // followed by setter selector name
4379/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004380/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004381/// kPropertyWeak = 'W' // 'weak' property
4382/// kPropertyStrong = 'P' // property GC'able
4383/// kPropertyNonAtomic = 'N' // property non-atomic
4384/// };
4385/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004386void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004387 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004388 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004389 // Collect information from the property implementation decl(s).
4390 bool Dynamic = false;
4391 ObjCPropertyImplDecl *SynthesizePID = 0;
4392
4393 // FIXME: Duplicated code due to poor abstraction.
4394 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004395 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004396 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4397 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004398 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004399 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004400 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004401 if (PID->getPropertyDecl() == PD) {
4402 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4403 Dynamic = true;
4404 } else {
4405 SynthesizePID = PID;
4406 }
4407 }
4408 }
4409 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004410 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004411 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004412 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004413 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004414 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004415 if (PID->getPropertyDecl() == PD) {
4416 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4417 Dynamic = true;
4418 } else {
4419 SynthesizePID = PID;
4420 }
4421 }
Mike Stump11289f42009-09-09 15:08:12 +00004422 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004423 }
4424 }
4425
4426 // FIXME: This is not very efficient.
4427 S = "T";
4428
4429 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004430 // GCC has some special rules regarding encoding of properties which
4431 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004432 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004433 true /* outermost type */,
4434 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004435
4436 if (PD->isReadOnly()) {
4437 S += ",R";
4438 } else {
4439 switch (PD->getSetterKind()) {
4440 case ObjCPropertyDecl::Assign: break;
4441 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004442 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004443 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004444 }
4445 }
4446
4447 // It really isn't clear at all what this means, since properties
4448 // are "dynamic by default".
4449 if (Dynamic)
4450 S += ",D";
4451
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004452 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4453 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004454
Daniel Dunbar4932b362008-08-28 04:38:10 +00004455 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4456 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004457 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004458 }
4459
4460 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4461 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004462 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004463 }
4464
4465 if (SynthesizePID) {
4466 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4467 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004468 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004469 }
4470
4471 // FIXME: OBJCGC: weak & strong
4472}
4473
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004474/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004475/// Another legacy compatibility encoding: 32-bit longs are encoded as
4476/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004477/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4478///
4479void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004480 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004481 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004482 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004483 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004484 else
Jay Foad39c79802011-01-12 09:06:06 +00004485 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004486 PointeeTy = IntTy;
4487 }
4488 }
4489}
4490
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004491void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004492 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004493 // We follow the behavior of gcc, expanding structures which are
4494 // directly pointed to, and expanding embedded structures. Note that
4495 // these rules are sufficient to prevent recursive encoding of the
4496 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004497 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004498 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004499}
4500
David Chisnallb190a2c2010-06-04 01:10:52 +00004501static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4502 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004503 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004504 case BuiltinType::Void: return 'v';
4505 case BuiltinType::Bool: return 'B';
4506 case BuiltinType::Char_U:
4507 case BuiltinType::UChar: return 'C';
4508 case BuiltinType::UShort: return 'S';
4509 case BuiltinType::UInt: return 'I';
4510 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004511 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004512 case BuiltinType::UInt128: return 'T';
4513 case BuiltinType::ULongLong: return 'Q';
4514 case BuiltinType::Char_S:
4515 case BuiltinType::SChar: return 'c';
4516 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004517 case BuiltinType::WChar_S:
4518 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004519 case BuiltinType::Int: return 'i';
4520 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004521 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004522 case BuiltinType::LongLong: return 'q';
4523 case BuiltinType::Int128: return 't';
4524 case BuiltinType::Float: return 'f';
4525 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004526 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004527 }
4528}
4529
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004530static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4531 EnumDecl *Enum = ET->getDecl();
4532
4533 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4534 if (!Enum->isFixed())
4535 return 'i';
4536
4537 // The encoding of a fixed enum type matches its fixed underlying type.
4538 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4539}
4540
Jay Foad39c79802011-01-12 09:06:06 +00004541static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004542 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004543 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004544 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004545 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4546 // The GNU runtime requires more information; bitfields are encoded as b,
4547 // then the offset (in bits) of the first element, then the type of the
4548 // bitfield, then the size in bits. For example, in this structure:
4549 //
4550 // struct
4551 // {
4552 // int integer;
4553 // int flags:2;
4554 // };
4555 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4556 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4557 // information is not especially sensible, but we're stuck with it for
4558 // compatibility with GCC, although providing it breaks anything that
4559 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004560 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004561 const RecordDecl *RD = FD->getParent();
4562 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004563 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004564 if (const EnumType *ET = T->getAs<EnumType>())
4565 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004566 else
Jay Foad39c79802011-01-12 09:06:06 +00004567 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004568 }
Richard Smithcaf33902011-10-10 18:28:20 +00004569 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004570}
4571
Daniel Dunbar07d07852009-10-18 21:17:35 +00004572// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004573void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4574 bool ExpandPointedToStructures,
4575 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004576 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004577 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004578 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004579 bool StructField,
4580 bool EncodeBlockParameters,
4581 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004582 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004583 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004584 return EncodeBitField(this, S, T, FD);
4585 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004586 return;
4587 }
Mike Stump11289f42009-09-09 15:08:12 +00004588
John McCall9dd450b2009-09-21 23:43:11 +00004589 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004590 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004591 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004592 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004593 return;
4594 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004595
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004596 // encoding for pointer or r3eference types.
4597 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004598 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004599 if (PT->isObjCSelType()) {
4600 S += ':';
4601 return;
4602 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004603 PointeeTy = PT->getPointeeType();
4604 }
4605 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4606 PointeeTy = RT->getPointeeType();
4607 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004608 bool isReadOnly = false;
4609 // For historical/compatibility reasons, the read-only qualifier of the
4610 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4611 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004612 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004613 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004614 if (OutermostType && T.isConstQualified()) {
4615 isReadOnly = true;
4616 S += 'r';
4617 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004618 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004619 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004620 while (P->getAs<PointerType>())
4621 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004622 if (P.isConstQualified()) {
4623 isReadOnly = true;
4624 S += 'r';
4625 }
4626 }
4627 if (isReadOnly) {
4628 // Another legacy compatibility encoding. Some ObjC qualifier and type
4629 // combinations need to be rearranged.
4630 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004631 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004632 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004633 }
Mike Stump11289f42009-09-09 15:08:12 +00004634
Anders Carlssond8499822007-10-29 05:01:08 +00004635 if (PointeeTy->isCharType()) {
4636 // char pointer types should be encoded as '*' unless it is a
4637 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004638 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004639 S += '*';
4640 return;
4641 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004642 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004643 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4644 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4645 S += '#';
4646 return;
4647 }
4648 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4649 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4650 S += '@';
4651 return;
4652 }
4653 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004654 }
Anders Carlssond8499822007-10-29 05:01:08 +00004655 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004656 getLegacyIntegralTypeEncoding(PointeeTy);
4657
Mike Stump11289f42009-09-09 15:08:12 +00004658 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004659 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004660 return;
4661 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004662
Chris Lattnere7cabb92009-07-13 00:10:46 +00004663 if (const ArrayType *AT =
4664 // Ignore type qualifiers etc.
4665 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004666 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004667 // Incomplete arrays are encoded as a pointer to the array element.
4668 S += '^';
4669
Mike Stump11289f42009-09-09 15:08:12 +00004670 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004671 false, ExpandStructures, FD);
4672 } else {
4673 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004674
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004675 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4676 if (getTypeSize(CAT->getElementType()) == 0)
4677 S += '0';
4678 else
4679 S += llvm::utostr(CAT->getSize().getZExtValue());
4680 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004681 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004682 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4683 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004684 S += '0';
4685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
4687 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004688 false, ExpandStructures, FD);
4689 S += ']';
4690 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004691 return;
4692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693
John McCall9dd450b2009-09-21 23:43:11 +00004694 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004695 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004696 return;
4697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004699 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004700 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004701 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004702 // Anonymous structures print as '?'
4703 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4704 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004705 if (ClassTemplateSpecializationDecl *Spec
4706 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4707 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4708 std::string TemplateArgsStr
4709 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004710 TemplateArgs.data(),
4711 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004712 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004713
4714 S += TemplateArgsStr;
4715 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004716 } else {
4717 S += '?';
4718 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004719 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004720 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004721 if (!RDecl->isUnion()) {
4722 getObjCEncodingForStructureImpl(RDecl, S, FD);
4723 } else {
4724 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4725 FieldEnd = RDecl->field_end();
4726 Field != FieldEnd; ++Field) {
4727 if (FD) {
4728 S += '"';
4729 S += Field->getNameAsString();
4730 S += '"';
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004733 // Special case bit-fields.
4734 if (Field->isBitField()) {
4735 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004736 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004737 } else {
4738 QualType qt = Field->getType();
4739 getLegacyIntegralTypeEncoding(qt);
4740 getObjCEncodingForTypeImpl(qt, S, false, true,
4741 FD, /*OutermostType*/false,
4742 /*EncodingProperty*/false,
4743 /*StructField*/true);
4744 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004745 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004746 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004747 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004748 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004749 return;
4750 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004751
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004752 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004753 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004754 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004755 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004756 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004757 return;
4758 }
Mike Stump11289f42009-09-09 15:08:12 +00004759
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004760 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004761 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004762 if (EncodeBlockParameters) {
4763 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4764
4765 S += '<';
4766 // Block return type
4767 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4768 ExpandPointedToStructures, ExpandStructures,
4769 FD,
4770 false /* OutermostType */,
4771 EncodingProperty,
4772 false /* StructField */,
4773 EncodeBlockParameters,
4774 EncodeClassNames);
4775 // Block self
4776 S += "@?";
4777 // Block parameters
4778 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4779 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4780 E = FPT->arg_type_end(); I && (I != E); ++I) {
4781 getObjCEncodingForTypeImpl(*I, S,
4782 ExpandPointedToStructures,
4783 ExpandStructures,
4784 FD,
4785 false /* OutermostType */,
4786 EncodingProperty,
4787 false /* StructField */,
4788 EncodeBlockParameters,
4789 EncodeClassNames);
4790 }
4791 }
4792 S += '>';
4793 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004794 return;
4795 }
Mike Stump11289f42009-09-09 15:08:12 +00004796
John McCall8b07ec22010-05-15 11:32:37 +00004797 // Ignore protocol qualifiers when mangling at this level.
4798 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4799 T = OT->getBaseType();
4800
John McCall8ccfcb52009-09-24 19:53:00 +00004801 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004802 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004803 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004804 S += '{';
4805 const IdentifierInfo *II = OI->getIdentifier();
4806 S += II->getName();
4807 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004808 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004809 DeepCollectObjCIvars(OI, true, Ivars);
4810 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004811 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004812 if (Field->isBitField())
4813 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004814 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004815 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004816 }
4817 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004818 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004819 }
Mike Stump11289f42009-09-09 15:08:12 +00004820
John McCall9dd450b2009-09-21 23:43:11 +00004821 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004822 if (OPT->isObjCIdType()) {
4823 S += '@';
4824 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004825 }
Mike Stump11289f42009-09-09 15:08:12 +00004826
Steve Narofff0c86112009-10-28 22:03:49 +00004827 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4828 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4829 // Since this is a binary compatibility issue, need to consult with runtime
4830 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004831 S += '#';
4832 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004833 }
Mike Stump11289f42009-09-09 15:08:12 +00004834
Chris Lattnere7cabb92009-07-13 00:10:46 +00004835 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004836 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004837 ExpandPointedToStructures,
4838 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004839 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004840 // Note that we do extended encoding of protocol qualifer list
4841 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004842 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004843 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4844 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004845 S += '<';
4846 S += (*I)->getNameAsString();
4847 S += '>';
4848 }
4849 S += '"';
4850 }
4851 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004852 }
Mike Stump11289f42009-09-09 15:08:12 +00004853
Chris Lattnere7cabb92009-07-13 00:10:46 +00004854 QualType PointeeTy = OPT->getPointeeType();
4855 if (!EncodingProperty &&
4856 isa<TypedefType>(PointeeTy.getTypePtr())) {
4857 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004858 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004859 // {...};
4860 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004861 getObjCEncodingForTypeImpl(PointeeTy, S,
4862 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004863 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004864 return;
4865 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004866
4867 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004868 if (OPT->getInterfaceDecl() &&
4869 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004870 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004871 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004872 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4873 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004874 S += '<';
4875 S += (*I)->getNameAsString();
4876 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004877 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004878 S += '"';
4879 }
4880 return;
4881 }
Mike Stump11289f42009-09-09 15:08:12 +00004882
John McCalla9e6e8d2010-05-17 23:56:34 +00004883 // gcc just blithely ignores member pointers.
4884 // TODO: maybe there should be a mangling for these
4885 if (T->getAs<MemberPointerType>())
4886 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004887
4888 if (T->isVectorType()) {
4889 // This matches gcc's encoding, even though technically it is
4890 // insufficient.
4891 // FIXME. We should do a better job than gcc.
4892 return;
4893 }
4894
David Blaikie83d382b2011-09-23 05:06:16 +00004895 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004896}
4897
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004898void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4899 std::string &S,
4900 const FieldDecl *FD,
4901 bool includeVBases) const {
4902 assert(RDecl && "Expected non-null RecordDecl");
4903 assert(!RDecl->isUnion() && "Should not be called for unions");
4904 if (!RDecl->getDefinition())
4905 return;
4906
4907 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4908 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4909 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4910
4911 if (CXXRec) {
4912 for (CXXRecordDecl::base_class_iterator
4913 BI = CXXRec->bases_begin(),
4914 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4915 if (!BI->isVirtual()) {
4916 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004917 if (base->isEmpty())
4918 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004919 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004920 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4921 std::make_pair(offs, base));
4922 }
4923 }
4924 }
4925
4926 unsigned i = 0;
4927 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4928 FieldEnd = RDecl->field_end();
4929 Field != FieldEnd; ++Field, ++i) {
4930 uint64_t offs = layout.getFieldOffset(i);
4931 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004932 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004933 }
4934
4935 if (CXXRec && includeVBases) {
4936 for (CXXRecordDecl::base_class_iterator
4937 BI = CXXRec->vbases_begin(),
4938 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4939 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004940 if (base->isEmpty())
4941 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004942 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004943 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4944 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4945 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004946 }
4947 }
4948
4949 CharUnits size;
4950 if (CXXRec) {
4951 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4952 } else {
4953 size = layout.getSize();
4954 }
4955
4956 uint64_t CurOffs = 0;
4957 std::multimap<uint64_t, NamedDecl *>::iterator
4958 CurLayObj = FieldOrBaseOffsets.begin();
4959
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004960 if (CXXRec && CXXRec->isDynamicClass() &&
4961 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004962 if (FD) {
4963 S += "\"_vptr$";
4964 std::string recname = CXXRec->getNameAsString();
4965 if (recname.empty()) recname = "?";
4966 S += recname;
4967 S += '"';
4968 }
4969 S += "^^?";
4970 CurOffs += getTypeSize(VoidPtrTy);
4971 }
4972
4973 if (!RDecl->hasFlexibleArrayMember()) {
4974 // Mark the end of the structure.
4975 uint64_t offs = toBits(size);
4976 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4977 std::make_pair(offs, (NamedDecl*)0));
4978 }
4979
4980 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4981 assert(CurOffs <= CurLayObj->first);
4982
4983 if (CurOffs < CurLayObj->first) {
4984 uint64_t padding = CurLayObj->first - CurOffs;
4985 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4986 // packing/alignment of members is different that normal, in which case
4987 // the encoding will be out-of-sync with the real layout.
4988 // If the runtime switches to just consider the size of types without
4989 // taking into account alignment, we could make padding explicit in the
4990 // encoding (e.g. using arrays of chars). The encoding strings would be
4991 // longer then though.
4992 CurOffs += padding;
4993 }
4994
4995 NamedDecl *dcl = CurLayObj->second;
4996 if (dcl == 0)
4997 break; // reached end of structure.
4998
4999 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5000 // We expand the bases without their virtual bases since those are going
5001 // in the initial structure. Note that this differs from gcc which
5002 // expands virtual bases each time one is encountered in the hierarchy,
5003 // making the encoding type bigger than it really is.
5004 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005005 assert(!base->isEmpty());
5006 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005007 } else {
5008 FieldDecl *field = cast<FieldDecl>(dcl);
5009 if (FD) {
5010 S += '"';
5011 S += field->getNameAsString();
5012 S += '"';
5013 }
5014
5015 if (field->isBitField()) {
5016 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005017 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005018 } else {
5019 QualType qt = field->getType();
5020 getLegacyIntegralTypeEncoding(qt);
5021 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5022 /*OutermostType*/false,
5023 /*EncodingProperty*/false,
5024 /*StructField*/true);
5025 CurOffs += getTypeSize(field->getType());
5026 }
5027 }
5028 }
5029}
5030
Mike Stump11289f42009-09-09 15:08:12 +00005031void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005032 std::string& S) const {
5033 if (QT & Decl::OBJC_TQ_In)
5034 S += 'n';
5035 if (QT & Decl::OBJC_TQ_Inout)
5036 S += 'N';
5037 if (QT & Decl::OBJC_TQ_Out)
5038 S += 'o';
5039 if (QT & Decl::OBJC_TQ_Bycopy)
5040 S += 'O';
5041 if (QT & Decl::OBJC_TQ_Byref)
5042 S += 'R';
5043 if (QT & Decl::OBJC_TQ_Oneway)
5044 S += 'V';
5045}
5046
Douglas Gregor3ea72692011-08-12 05:46:01 +00005047TypedefDecl *ASTContext::getObjCIdDecl() const {
5048 if (!ObjCIdDecl) {
5049 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5050 T = getObjCObjectPointerType(T);
5051 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5052 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5053 getTranslationUnitDecl(),
5054 SourceLocation(), SourceLocation(),
5055 &Idents.get("id"), IdInfo);
5056 }
5057
5058 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005059}
5060
Douglas Gregor52e02802011-08-12 06:17:30 +00005061TypedefDecl *ASTContext::getObjCSelDecl() const {
5062 if (!ObjCSelDecl) {
5063 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5064 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5065 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5066 getTranslationUnitDecl(),
5067 SourceLocation(), SourceLocation(),
5068 &Idents.get("SEL"), SelInfo);
5069 }
5070 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005071}
5072
Douglas Gregor0a586182011-08-12 05:59:41 +00005073TypedefDecl *ASTContext::getObjCClassDecl() const {
5074 if (!ObjCClassDecl) {
5075 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5076 T = getObjCObjectPointerType(T);
5077 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5078 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5079 getTranslationUnitDecl(),
5080 SourceLocation(), SourceLocation(),
5081 &Idents.get("Class"), ClassInfo);
5082 }
5083
5084 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005085}
5086
Douglas Gregord53ae832012-01-17 18:09:05 +00005087ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5088 if (!ObjCProtocolClassDecl) {
5089 ObjCProtocolClassDecl
5090 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5091 SourceLocation(),
5092 &Idents.get("Protocol"),
5093 /*PrevDecl=*/0,
5094 SourceLocation(), true);
5095 }
5096
5097 return ObjCProtocolClassDecl;
5098}
5099
Meador Inge5d3fb222012-06-16 03:34:49 +00005100//===----------------------------------------------------------------------===//
5101// __builtin_va_list Construction Functions
5102//===----------------------------------------------------------------------===//
5103
5104static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5105 // typedef char* __builtin_va_list;
5106 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5107 TypeSourceInfo *TInfo
5108 = Context->getTrivialTypeSourceInfo(CharPtrType);
5109
5110 TypedefDecl *VaListTypeDecl
5111 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5112 Context->getTranslationUnitDecl(),
5113 SourceLocation(), SourceLocation(),
5114 &Context->Idents.get("__builtin_va_list"),
5115 TInfo);
5116 return VaListTypeDecl;
5117}
5118
5119static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5120 // typedef void* __builtin_va_list;
5121 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5122 TypeSourceInfo *TInfo
5123 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5124
5125 TypedefDecl *VaListTypeDecl
5126 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5127 Context->getTranslationUnitDecl(),
5128 SourceLocation(), SourceLocation(),
5129 &Context->Idents.get("__builtin_va_list"),
5130 TInfo);
5131 return VaListTypeDecl;
5132}
5133
5134static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5135 // typedef struct __va_list_tag {
5136 RecordDecl *VaListTagDecl;
5137
5138 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5139 Context->getTranslationUnitDecl(),
5140 &Context->Idents.get("__va_list_tag"));
5141 VaListTagDecl->startDefinition();
5142
5143 const size_t NumFields = 5;
5144 QualType FieldTypes[NumFields];
5145 const char *FieldNames[NumFields];
5146
5147 // unsigned char gpr;
5148 FieldTypes[0] = Context->UnsignedCharTy;
5149 FieldNames[0] = "gpr";
5150
5151 // unsigned char fpr;
5152 FieldTypes[1] = Context->UnsignedCharTy;
5153 FieldNames[1] = "fpr";
5154
5155 // unsigned short reserved;
5156 FieldTypes[2] = Context->UnsignedShortTy;
5157 FieldNames[2] = "reserved";
5158
5159 // void* overflow_arg_area;
5160 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5161 FieldNames[3] = "overflow_arg_area";
5162
5163 // void* reg_save_area;
5164 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5165 FieldNames[4] = "reg_save_area";
5166
5167 // Create fields
5168 for (unsigned i = 0; i < NumFields; ++i) {
5169 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5170 SourceLocation(),
5171 SourceLocation(),
5172 &Context->Idents.get(FieldNames[i]),
5173 FieldTypes[i], /*TInfo=*/0,
5174 /*BitWidth=*/0,
5175 /*Mutable=*/false,
5176 ICIS_NoInit);
5177 Field->setAccess(AS_public);
5178 VaListTagDecl->addDecl(Field);
5179 }
5180 VaListTagDecl->completeDefinition();
5181 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005182 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005183
5184 // } __va_list_tag;
5185 TypedefDecl *VaListTagTypedefDecl
5186 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5187 Context->getTranslationUnitDecl(),
5188 SourceLocation(), SourceLocation(),
5189 &Context->Idents.get("__va_list_tag"),
5190 Context->getTrivialTypeSourceInfo(VaListTagType));
5191 QualType VaListTagTypedefType =
5192 Context->getTypedefType(VaListTagTypedefDecl);
5193
5194 // typedef __va_list_tag __builtin_va_list[1];
5195 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5196 QualType VaListTagArrayType
5197 = Context->getConstantArrayType(VaListTagTypedefType,
5198 Size, ArrayType::Normal, 0);
5199 TypeSourceInfo *TInfo
5200 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5201 TypedefDecl *VaListTypedefDecl
5202 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5203 Context->getTranslationUnitDecl(),
5204 SourceLocation(), SourceLocation(),
5205 &Context->Idents.get("__builtin_va_list"),
5206 TInfo);
5207
5208 return VaListTypedefDecl;
5209}
5210
5211static TypedefDecl *
5212CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5213 // typedef struct __va_list_tag {
5214 RecordDecl *VaListTagDecl;
5215 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5216 Context->getTranslationUnitDecl(),
5217 &Context->Idents.get("__va_list_tag"));
5218 VaListTagDecl->startDefinition();
5219
5220 const size_t NumFields = 4;
5221 QualType FieldTypes[NumFields];
5222 const char *FieldNames[NumFields];
5223
5224 // unsigned gp_offset;
5225 FieldTypes[0] = Context->UnsignedIntTy;
5226 FieldNames[0] = "gp_offset";
5227
5228 // unsigned fp_offset;
5229 FieldTypes[1] = Context->UnsignedIntTy;
5230 FieldNames[1] = "fp_offset";
5231
5232 // void* overflow_arg_area;
5233 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5234 FieldNames[2] = "overflow_arg_area";
5235
5236 // void* reg_save_area;
5237 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5238 FieldNames[3] = "reg_save_area";
5239
5240 // Create fields
5241 for (unsigned i = 0; i < NumFields; ++i) {
5242 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5243 VaListTagDecl,
5244 SourceLocation(),
5245 SourceLocation(),
5246 &Context->Idents.get(FieldNames[i]),
5247 FieldTypes[i], /*TInfo=*/0,
5248 /*BitWidth=*/0,
5249 /*Mutable=*/false,
5250 ICIS_NoInit);
5251 Field->setAccess(AS_public);
5252 VaListTagDecl->addDecl(Field);
5253 }
5254 VaListTagDecl->completeDefinition();
5255 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005256 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005257
5258 // } __va_list_tag;
5259 TypedefDecl *VaListTagTypedefDecl
5260 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5261 Context->getTranslationUnitDecl(),
5262 SourceLocation(), SourceLocation(),
5263 &Context->Idents.get("__va_list_tag"),
5264 Context->getTrivialTypeSourceInfo(VaListTagType));
5265 QualType VaListTagTypedefType =
5266 Context->getTypedefType(VaListTagTypedefDecl);
5267
5268 // typedef __va_list_tag __builtin_va_list[1];
5269 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5270 QualType VaListTagArrayType
5271 = Context->getConstantArrayType(VaListTagTypedefType,
5272 Size, ArrayType::Normal,0);
5273 TypeSourceInfo *TInfo
5274 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5275 TypedefDecl *VaListTypedefDecl
5276 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5277 Context->getTranslationUnitDecl(),
5278 SourceLocation(), SourceLocation(),
5279 &Context->Idents.get("__builtin_va_list"),
5280 TInfo);
5281
5282 return VaListTypedefDecl;
5283}
5284
5285static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5286 // typedef int __builtin_va_list[4];
5287 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5288 QualType IntArrayType
5289 = Context->getConstantArrayType(Context->IntTy,
5290 Size, ArrayType::Normal, 0);
5291 TypedefDecl *VaListTypedefDecl
5292 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5293 Context->getTranslationUnitDecl(),
5294 SourceLocation(), SourceLocation(),
5295 &Context->Idents.get("__builtin_va_list"),
5296 Context->getTrivialTypeSourceInfo(IntArrayType));
5297
5298 return VaListTypedefDecl;
5299}
5300
5301static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5302 TargetInfo::BuiltinVaListKind Kind) {
5303 switch (Kind) {
5304 case TargetInfo::CharPtrBuiltinVaList:
5305 return CreateCharPtrBuiltinVaListDecl(Context);
5306 case TargetInfo::VoidPtrBuiltinVaList:
5307 return CreateVoidPtrBuiltinVaListDecl(Context);
5308 case TargetInfo::PowerABIBuiltinVaList:
5309 return CreatePowerABIBuiltinVaListDecl(Context);
5310 case TargetInfo::X86_64ABIBuiltinVaList:
5311 return CreateX86_64ABIBuiltinVaListDecl(Context);
5312 case TargetInfo::PNaClABIBuiltinVaList:
5313 return CreatePNaClABIBuiltinVaListDecl(Context);
5314 }
5315
5316 llvm_unreachable("Unhandled __builtin_va_list type kind");
5317}
5318
5319TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5320 if (!BuiltinVaListDecl)
5321 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5322
5323 return BuiltinVaListDecl;
5324}
5325
Meador Ingecfb60902012-07-01 15:57:25 +00005326QualType ASTContext::getVaListTagType() const {
5327 // Force the creation of VaListTagTy by building the __builtin_va_list
5328 // declaration.
5329 if (VaListTagTy.isNull())
5330 (void) getBuiltinVaListDecl();
5331
5332 return VaListTagTy;
5333}
5334
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005335void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005336 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005337 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005338
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005339 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005340}
5341
John McCalld28ae272009-12-02 08:04:21 +00005342/// \brief Retrieve the template name that corresponds to a non-empty
5343/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005344TemplateName
5345ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5346 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005347 unsigned size = End - Begin;
5348 assert(size > 1 && "set is not overloaded!");
5349
5350 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5351 size * sizeof(FunctionTemplateDecl*));
5352 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5353
5354 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005355 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005356 NamedDecl *D = *I;
5357 assert(isa<FunctionTemplateDecl>(D) ||
5358 (isa<UsingShadowDecl>(D) &&
5359 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5360 *Storage++ = D;
5361 }
5362
5363 return TemplateName(OT);
5364}
5365
Douglas Gregordc572a32009-03-30 22:58:21 +00005366/// \brief Retrieve the template name that represents a qualified
5367/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005368TemplateName
5369ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5370 bool TemplateKeyword,
5371 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005372 assert(NNS && "Missing nested-name-specifier in qualified template name");
5373
Douglas Gregorc42075a2010-02-04 18:10:26 +00005374 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005375 llvm::FoldingSetNodeID ID;
5376 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5377
5378 void *InsertPos = 0;
5379 QualifiedTemplateName *QTN =
5380 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5381 if (!QTN) {
5382 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5383 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5384 }
5385
5386 return TemplateName(QTN);
5387}
5388
5389/// \brief Retrieve the template name that represents a dependent
5390/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005391TemplateName
5392ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5393 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005394 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005395 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005396
5397 llvm::FoldingSetNodeID ID;
5398 DependentTemplateName::Profile(ID, NNS, Name);
5399
5400 void *InsertPos = 0;
5401 DependentTemplateName *QTN =
5402 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5403
5404 if (QTN)
5405 return TemplateName(QTN);
5406
5407 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5408 if (CanonNNS == NNS) {
5409 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5410 } else {
5411 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5412 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005413 DependentTemplateName *CheckQTN =
5414 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5415 assert(!CheckQTN && "Dependent type name canonicalization broken");
5416 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005417 }
5418
5419 DependentTemplateNames.InsertNode(QTN, InsertPos);
5420 return TemplateName(QTN);
5421}
5422
Douglas Gregor71395fa2009-11-04 00:56:37 +00005423/// \brief Retrieve the template name that represents a dependent
5424/// template name such as \c MetaFun::template operator+.
5425TemplateName
5426ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005427 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005428 assert((!NNS || NNS->isDependent()) &&
5429 "Nested name specifier must be dependent");
5430
5431 llvm::FoldingSetNodeID ID;
5432 DependentTemplateName::Profile(ID, NNS, Operator);
5433
5434 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005435 DependentTemplateName *QTN
5436 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005437
5438 if (QTN)
5439 return TemplateName(QTN);
5440
5441 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5442 if (CanonNNS == NNS) {
5443 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5444 } else {
5445 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5446 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005447
5448 DependentTemplateName *CheckQTN
5449 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5450 assert(!CheckQTN && "Dependent template name canonicalization broken");
5451 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005452 }
5453
5454 DependentTemplateNames.InsertNode(QTN, InsertPos);
5455 return TemplateName(QTN);
5456}
5457
Douglas Gregor5590be02011-01-15 06:45:20 +00005458TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005459ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5460 TemplateName replacement) const {
5461 llvm::FoldingSetNodeID ID;
5462 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5463
5464 void *insertPos = 0;
5465 SubstTemplateTemplateParmStorage *subst
5466 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5467
5468 if (!subst) {
5469 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5470 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5471 }
5472
5473 return TemplateName(subst);
5474}
5475
5476TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005477ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5478 const TemplateArgument &ArgPack) const {
5479 ASTContext &Self = const_cast<ASTContext &>(*this);
5480 llvm::FoldingSetNodeID ID;
5481 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5482
5483 void *InsertPos = 0;
5484 SubstTemplateTemplateParmPackStorage *Subst
5485 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5486
5487 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005488 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005489 ArgPack.pack_size(),
5490 ArgPack.pack_begin());
5491 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5492 }
5493
5494 return TemplateName(Subst);
5495}
5496
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005497/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005498/// TargetInfo, produce the corresponding type. The unsigned @p Type
5499/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005500CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005501 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005502 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005503 case TargetInfo::SignedShort: return ShortTy;
5504 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5505 case TargetInfo::SignedInt: return IntTy;
5506 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5507 case TargetInfo::SignedLong: return LongTy;
5508 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5509 case TargetInfo::SignedLongLong: return LongLongTy;
5510 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5511 }
5512
David Blaikie83d382b2011-09-23 05:06:16 +00005513 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005514}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005515
5516//===----------------------------------------------------------------------===//
5517// Type Predicates.
5518//===----------------------------------------------------------------------===//
5519
Fariborz Jahanian96207692009-02-18 21:49:28 +00005520/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5521/// garbage collection attribute.
5522///
John McCall553d45a2011-01-12 00:34:59 +00005523Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005524 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005525 return Qualifiers::GCNone;
5526
David Blaikiebbafb8a2012-03-11 07:00:24 +00005527 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005528 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5529
5530 // Default behaviour under objective-C's gc is for ObjC pointers
5531 // (or pointers to them) be treated as though they were declared
5532 // as __strong.
5533 if (GCAttrs == Qualifiers::GCNone) {
5534 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5535 return Qualifiers::Strong;
5536 else if (Ty->isPointerType())
5537 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5538 } else {
5539 // It's not valid to set GC attributes on anything that isn't a
5540 // pointer.
5541#ifndef NDEBUG
5542 QualType CT = Ty->getCanonicalTypeInternal();
5543 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5544 CT = AT->getElementType();
5545 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5546#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005547 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005548 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005549}
5550
Chris Lattner49af6a42008-04-07 06:51:04 +00005551//===----------------------------------------------------------------------===//
5552// Type Compatibility Testing
5553//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005554
Mike Stump11289f42009-09-09 15:08:12 +00005555/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005556/// compatible.
5557static bool areCompatVectorTypes(const VectorType *LHS,
5558 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005559 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005560 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005561 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005562}
5563
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005564bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5565 QualType SecondVec) {
5566 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5567 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5568
5569 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5570 return true;
5571
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005572 // Treat Neon vector types and most AltiVec vector types as if they are the
5573 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005574 const VectorType *First = FirstVec->getAs<VectorType>();
5575 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005576 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005577 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005578 First->getVectorKind() != VectorType::AltiVecPixel &&
5579 First->getVectorKind() != VectorType::AltiVecBool &&
5580 Second->getVectorKind() != VectorType::AltiVecPixel &&
5581 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005582 return true;
5583
5584 return false;
5585}
5586
Steve Naroff8e6aee52009-07-23 01:01:38 +00005587//===----------------------------------------------------------------------===//
5588// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5589//===----------------------------------------------------------------------===//
5590
5591/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5592/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005593bool
5594ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5595 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005596 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005597 return true;
5598 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5599 E = rProto->protocol_end(); PI != E; ++PI)
5600 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5601 return true;
5602 return false;
5603}
5604
Steve Naroff8e6aee52009-07-23 01:01:38 +00005605/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5606/// return true if lhs's protocols conform to rhs's protocol; false
5607/// otherwise.
5608bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5609 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5610 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5611 return false;
5612}
5613
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005614/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5615/// Class<p1, ...>.
5616bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5617 QualType rhs) {
5618 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5619 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5620 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5621
5622 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5623 E = lhsQID->qual_end(); I != E; ++I) {
5624 bool match = false;
5625 ObjCProtocolDecl *lhsProto = *I;
5626 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5627 E = rhsOPT->qual_end(); J != E; ++J) {
5628 ObjCProtocolDecl *rhsProto = *J;
5629 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5630 match = true;
5631 break;
5632 }
5633 }
5634 if (!match)
5635 return false;
5636 }
5637 return true;
5638}
5639
Steve Naroff8e6aee52009-07-23 01:01:38 +00005640/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5641/// ObjCQualifiedIDType.
5642bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5643 bool compare) {
5644 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005645 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005646 lhs->isObjCIdType() || lhs->isObjCClassType())
5647 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005648 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005649 rhs->isObjCIdType() || rhs->isObjCClassType())
5650 return true;
5651
5652 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005653 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005654
Steve Naroff8e6aee52009-07-23 01:01:38 +00005655 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005656
Steve Naroff8e6aee52009-07-23 01:01:38 +00005657 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005658 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005659 // make sure we check the class hierarchy.
5660 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5661 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5662 E = lhsQID->qual_end(); I != E; ++I) {
5663 // when comparing an id<P> on lhs with a static type on rhs,
5664 // see if static class implements all of id's protocols, directly or
5665 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005666 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005667 return false;
5668 }
5669 }
5670 // If there are no qualifiers and no interface, we have an 'id'.
5671 return true;
5672 }
Mike Stump11289f42009-09-09 15:08:12 +00005673 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005674 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5675 E = lhsQID->qual_end(); I != E; ++I) {
5676 ObjCProtocolDecl *lhsProto = *I;
5677 bool match = false;
5678
5679 // when comparing an id<P> on lhs with a static type on rhs,
5680 // see if static class implements all of id's protocols, directly or
5681 // through its super class and categories.
5682 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5683 E = rhsOPT->qual_end(); J != E; ++J) {
5684 ObjCProtocolDecl *rhsProto = *J;
5685 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5686 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5687 match = true;
5688 break;
5689 }
5690 }
Mike Stump11289f42009-09-09 15:08:12 +00005691 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005692 // make sure we check the class hierarchy.
5693 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5694 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5695 E = lhsQID->qual_end(); I != E; ++I) {
5696 // when comparing an id<P> on lhs with a static type on rhs,
5697 // see if static class implements all of id's protocols, directly or
5698 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005699 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005700 match = true;
5701 break;
5702 }
5703 }
5704 }
5705 if (!match)
5706 return false;
5707 }
Mike Stump11289f42009-09-09 15:08:12 +00005708
Steve Naroff8e6aee52009-07-23 01:01:38 +00005709 return true;
5710 }
Mike Stump11289f42009-09-09 15:08:12 +00005711
Steve Naroff8e6aee52009-07-23 01:01:38 +00005712 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5713 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5714
Mike Stump11289f42009-09-09 15:08:12 +00005715 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005716 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005717 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005718 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5719 E = lhsOPT->qual_end(); I != E; ++I) {
5720 ObjCProtocolDecl *lhsProto = *I;
5721 bool match = false;
5722
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005723 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005724 // see if static class implements all of id's protocols, directly or
5725 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005726 // First, lhs protocols in the qualifier list must be found, direct
5727 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005728 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5729 E = rhsQID->qual_end(); J != E; ++J) {
5730 ObjCProtocolDecl *rhsProto = *J;
5731 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5732 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5733 match = true;
5734 break;
5735 }
5736 }
5737 if (!match)
5738 return false;
5739 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005740
5741 // Static class's protocols, or its super class or category protocols
5742 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5743 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5744 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5745 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5746 // This is rather dubious but matches gcc's behavior. If lhs has
5747 // no type qualifier and its class has no static protocol(s)
5748 // assume that it is mismatch.
5749 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5750 return false;
5751 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5752 LHSInheritedProtocols.begin(),
5753 E = LHSInheritedProtocols.end(); I != E; ++I) {
5754 bool match = false;
5755 ObjCProtocolDecl *lhsProto = (*I);
5756 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5757 E = rhsQID->qual_end(); J != E; ++J) {
5758 ObjCProtocolDecl *rhsProto = *J;
5759 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5760 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5761 match = true;
5762 break;
5763 }
5764 }
5765 if (!match)
5766 return false;
5767 }
5768 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005769 return true;
5770 }
5771 return false;
5772}
5773
Eli Friedman47f77112008-08-22 00:56:42 +00005774/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005775/// compatible for assignment from RHS to LHS. This handles validation of any
5776/// protocol qualifiers on the LHS or RHS.
5777///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005778bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5779 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005780 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5781 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5782
Steve Naroff1329fa02009-07-15 18:40:39 +00005783 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005784 if (LHS->isObjCUnqualifiedIdOrClass() ||
5785 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005786 return true;
5787
John McCall8b07ec22010-05-15 11:32:37 +00005788 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005789 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5790 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005791 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005792
5793 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5794 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5795 QualType(RHSOPT,0));
5796
John McCall8b07ec22010-05-15 11:32:37 +00005797 // If we have 2 user-defined types, fall into that path.
5798 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005799 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005800
Steve Naroff8e6aee52009-07-23 01:01:38 +00005801 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005802}
5803
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005804/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005805/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005806/// arguments in block literals. When passed as arguments, passing 'A*' where
5807/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5808/// not OK. For the return type, the opposite is not OK.
5809bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5810 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005811 const ObjCObjectPointerType *RHSOPT,
5812 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005813 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005814 return true;
5815
5816 if (LHSOPT->isObjCBuiltinType()) {
5817 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5818 }
5819
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005820 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005821 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5822 QualType(RHSOPT,0),
5823 false);
5824
5825 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5826 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5827 if (LHS && RHS) { // We have 2 user-defined types.
5828 if (LHS != RHS) {
5829 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005830 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005831 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005832 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005833 }
5834 else
5835 return true;
5836 }
5837 return false;
5838}
5839
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005840/// getIntersectionOfProtocols - This routine finds the intersection of set
5841/// of protocols inherited from two distinct objective-c pointer objects.
5842/// It is used to build composite qualifier list of the composite type of
5843/// the conditional expression involving two objective-c pointer objects.
5844static
5845void getIntersectionOfProtocols(ASTContext &Context,
5846 const ObjCObjectPointerType *LHSOPT,
5847 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005848 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005849
John McCall8b07ec22010-05-15 11:32:37 +00005850 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5851 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5852 assert(LHS->getInterface() && "LHS must have an interface base");
5853 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005854
5855 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5856 unsigned LHSNumProtocols = LHS->getNumProtocols();
5857 if (LHSNumProtocols > 0)
5858 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5859 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005860 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005861 Context.CollectInheritedProtocols(LHS->getInterface(),
5862 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005863 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5864 LHSInheritedProtocols.end());
5865 }
5866
5867 unsigned RHSNumProtocols = RHS->getNumProtocols();
5868 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005869 ObjCProtocolDecl **RHSProtocols =
5870 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005871 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5872 if (InheritedProtocolSet.count(RHSProtocols[i]))
5873 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005874 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005875 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005876 Context.CollectInheritedProtocols(RHS->getInterface(),
5877 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005878 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5879 RHSInheritedProtocols.begin(),
5880 E = RHSInheritedProtocols.end(); I != E; ++I)
5881 if (InheritedProtocolSet.count((*I)))
5882 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005883 }
5884}
5885
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005886/// areCommonBaseCompatible - Returns common base class of the two classes if
5887/// one found. Note that this is O'2 algorithm. But it will be called as the
5888/// last type comparison in a ?-exp of ObjC pointer types before a
5889/// warning is issued. So, its invokation is extremely rare.
5890QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005891 const ObjCObjectPointerType *Lptr,
5892 const ObjCObjectPointerType *Rptr) {
5893 const ObjCObjectType *LHS = Lptr->getObjectType();
5894 const ObjCObjectType *RHS = Rptr->getObjectType();
5895 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5896 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005897 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005898 return QualType();
5899
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005900 do {
John McCall8b07ec22010-05-15 11:32:37 +00005901 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005902 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005903 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005904 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5905
5906 QualType Result = QualType(LHS, 0);
5907 if (!Protocols.empty())
5908 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5909 Result = getObjCObjectPointerType(Result);
5910 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005911 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005912 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005913
5914 return QualType();
5915}
5916
John McCall8b07ec22010-05-15 11:32:37 +00005917bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5918 const ObjCObjectType *RHS) {
5919 assert(LHS->getInterface() && "LHS is not an interface type");
5920 assert(RHS->getInterface() && "RHS is not an interface type");
5921
Chris Lattner49af6a42008-04-07 06:51:04 +00005922 // Verify that the base decls are compatible: the RHS must be a subclass of
5923 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005924 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005925 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005926
Chris Lattner49af6a42008-04-07 06:51:04 +00005927 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5928 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005929 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005930 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005931
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005932 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5933 // more detailed analysis is required.
5934 if (RHS->getNumProtocols() == 0) {
5935 // OK, if LHS is a superclass of RHS *and*
5936 // this superclass is assignment compatible with LHS.
5937 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005938 bool IsSuperClass =
5939 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5940 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005941 // OK if conversion of LHS to SuperClass results in narrowing of types
5942 // ; i.e., SuperClass may implement at least one of the protocols
5943 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5944 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5945 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005946 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005947 // If super class has no protocols, it is not a match.
5948 if (SuperClassInheritedProtocols.empty())
5949 return false;
5950
5951 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5952 LHSPE = LHS->qual_end();
5953 LHSPI != LHSPE; LHSPI++) {
5954 bool SuperImplementsProtocol = false;
5955 ObjCProtocolDecl *LHSProto = (*LHSPI);
5956
5957 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5958 SuperClassInheritedProtocols.begin(),
5959 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5960 ObjCProtocolDecl *SuperClassProto = (*I);
5961 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5962 SuperImplementsProtocol = true;
5963 break;
5964 }
5965 }
5966 if (!SuperImplementsProtocol)
5967 return false;
5968 }
5969 return true;
5970 }
5971 return false;
5972 }
Mike Stump11289f42009-09-09 15:08:12 +00005973
John McCall8b07ec22010-05-15 11:32:37 +00005974 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5975 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005976 LHSPI != LHSPE; LHSPI++) {
5977 bool RHSImplementsProtocol = false;
5978
5979 // If the RHS doesn't implement the protocol on the left, the types
5980 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005981 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5982 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005983 RHSPI != RHSPE; RHSPI++) {
5984 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005985 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005986 break;
5987 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005988 }
5989 // FIXME: For better diagnostics, consider passing back the protocol name.
5990 if (!RHSImplementsProtocol)
5991 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005992 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005993 // The RHS implements all protocols listed on the LHS.
5994 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005995}
5996
Steve Naroffb7605152009-02-12 17:52:19 +00005997bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5998 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005999 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6000 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006001
Steve Naroff7cae42b2009-07-10 23:34:53 +00006002 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006003 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006004
6005 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6006 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006007}
6008
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006009bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6010 return canAssignObjCInterfaces(
6011 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6012 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6013}
6014
Mike Stump11289f42009-09-09 15:08:12 +00006015/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006016/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006017/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006018/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006019bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6020 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006021 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006022 return hasSameType(LHS, RHS);
6023
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006024 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006025}
6026
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006027bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006028 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006029}
6030
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006031bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6032 return !mergeTypes(LHS, RHS, true).isNull();
6033}
6034
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006035/// mergeTransparentUnionType - if T is a transparent union type and a member
6036/// of T is compatible with SubType, return the merged type, else return
6037/// QualType()
6038QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6039 bool OfBlockPointer,
6040 bool Unqualified) {
6041 if (const RecordType *UT = T->getAsUnionType()) {
6042 RecordDecl *UD = UT->getDecl();
6043 if (UD->hasAttr<TransparentUnionAttr>()) {
6044 for (RecordDecl::field_iterator it = UD->field_begin(),
6045 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006046 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006047 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6048 if (!MT.isNull())
6049 return MT;
6050 }
6051 }
6052 }
6053
6054 return QualType();
6055}
6056
6057/// mergeFunctionArgumentTypes - merge two types which appear as function
6058/// argument types
6059QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6060 bool OfBlockPointer,
6061 bool Unqualified) {
6062 // GNU extension: two types are compatible if they appear as a function
6063 // argument, one of the types is a transparent union type and the other
6064 // type is compatible with a union member
6065 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6066 Unqualified);
6067 if (!lmerge.isNull())
6068 return lmerge;
6069
6070 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6071 Unqualified);
6072 if (!rmerge.isNull())
6073 return rmerge;
6074
6075 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6076}
6077
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006078QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006079 bool OfBlockPointer,
6080 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006081 const FunctionType *lbase = lhs->getAs<FunctionType>();
6082 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006083 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6084 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006085 bool allLTypes = true;
6086 bool allRTypes = true;
6087
6088 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006089 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006090 if (OfBlockPointer) {
6091 QualType RHS = rbase->getResultType();
6092 QualType LHS = lbase->getResultType();
6093 bool UnqualifiedResult = Unqualified;
6094 if (!UnqualifiedResult)
6095 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006096 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006097 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006098 else
John McCall8c6b56f2010-12-15 01:06:38 +00006099 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6100 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006101 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006102
6103 if (Unqualified)
6104 retType = retType.getUnqualifiedType();
6105
6106 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6107 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6108 if (Unqualified) {
6109 LRetType = LRetType.getUnqualifiedType();
6110 RRetType = RRetType.getUnqualifiedType();
6111 }
6112
6113 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006114 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006115 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006116 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006117
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006118 // FIXME: double check this
6119 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6120 // rbase->getRegParmAttr() != 0 &&
6121 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006122 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6123 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006124
Douglas Gregor8c940862010-01-18 17:14:39 +00006125 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006126 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006127 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006128
John McCall8c6b56f2010-12-15 01:06:38 +00006129 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006130 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6131 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006132 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6133 return QualType();
6134
John McCall31168b02011-06-15 23:02:42 +00006135 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6136 return QualType();
6137
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006138 // functypes which return are preferred over those that do not.
6139 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6140 allLTypes = false;
6141 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6142 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006143 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6144 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006145
John McCall31168b02011-06-15 23:02:42 +00006146 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006147
Eli Friedman47f77112008-08-22 00:56:42 +00006148 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006149 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6150 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006151 unsigned lproto_nargs = lproto->getNumArgs();
6152 unsigned rproto_nargs = rproto->getNumArgs();
6153
6154 // Compatible functions must have the same number of arguments
6155 if (lproto_nargs != rproto_nargs)
6156 return QualType();
6157
6158 // Variadic and non-variadic functions aren't compatible
6159 if (lproto->isVariadic() != rproto->isVariadic())
6160 return QualType();
6161
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006162 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6163 return QualType();
6164
Fariborz Jahanian97676972011-09-28 21:52:05 +00006165 if (LangOpts.ObjCAutoRefCount &&
6166 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6167 return QualType();
6168
Eli Friedman47f77112008-08-22 00:56:42 +00006169 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006170 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006171 for (unsigned i = 0; i < lproto_nargs; i++) {
6172 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6173 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006174 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6175 OfBlockPointer,
6176 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006177 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006178
6179 if (Unqualified)
6180 argtype = argtype.getUnqualifiedType();
6181
Eli Friedman47f77112008-08-22 00:56:42 +00006182 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006183 if (Unqualified) {
6184 largtype = largtype.getUnqualifiedType();
6185 rargtype = rargtype.getUnqualifiedType();
6186 }
6187
Chris Lattner465fa322008-10-05 17:34:18 +00006188 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6189 allLTypes = false;
6190 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6191 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006192 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006193
Eli Friedman47f77112008-08-22 00:56:42 +00006194 if (allLTypes) return lhs;
6195 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006196
6197 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6198 EPI.ExtInfo = einfo;
6199 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006200 }
6201
6202 if (lproto) allRTypes = false;
6203 if (rproto) allLTypes = false;
6204
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006205 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006206 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006207 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006208 if (proto->isVariadic()) return QualType();
6209 // Check that the types are compatible with the types that
6210 // would result from default argument promotions (C99 6.7.5.3p15).
6211 // The only types actually affected are promotable integer
6212 // types and floats, which would be passed as a different
6213 // type depending on whether the prototype is visible.
6214 unsigned proto_nargs = proto->getNumArgs();
6215 for (unsigned i = 0; i < proto_nargs; ++i) {
6216 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006217
6218 // Look at the promotion type of enum types, since that is the type used
6219 // to pass enum values.
6220 if (const EnumType *Enum = argTy->getAs<EnumType>())
6221 argTy = Enum->getDecl()->getPromotionType();
6222
Eli Friedman47f77112008-08-22 00:56:42 +00006223 if (argTy->isPromotableIntegerType() ||
6224 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6225 return QualType();
6226 }
6227
6228 if (allLTypes) return lhs;
6229 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006230
6231 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6232 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006233 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006234 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006235 }
6236
6237 if (allLTypes) return lhs;
6238 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006239 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006240}
6241
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006242QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006243 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006244 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006245 // C++ [expr]: If an expression initially has the type "reference to T", the
6246 // type is adjusted to "T" prior to any further analysis, the expression
6247 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006248 // expression is an lvalue unless the reference is an rvalue reference and
6249 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006250 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6251 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006252
6253 if (Unqualified) {
6254 LHS = LHS.getUnqualifiedType();
6255 RHS = RHS.getUnqualifiedType();
6256 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006257
Eli Friedman47f77112008-08-22 00:56:42 +00006258 QualType LHSCan = getCanonicalType(LHS),
6259 RHSCan = getCanonicalType(RHS);
6260
6261 // If two types are identical, they are compatible.
6262 if (LHSCan == RHSCan)
6263 return LHS;
6264
John McCall8ccfcb52009-09-24 19:53:00 +00006265 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006266 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6267 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006268 if (LQuals != RQuals) {
6269 // If any of these qualifiers are different, we have a type
6270 // mismatch.
6271 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006272 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6273 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006274 return QualType();
6275
6276 // Exactly one GC qualifier difference is allowed: __strong is
6277 // okay if the other type has no GC qualifier but is an Objective
6278 // C object pointer (i.e. implicitly strong by default). We fix
6279 // this by pretending that the unqualified type was actually
6280 // qualified __strong.
6281 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6282 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6283 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6284
6285 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6286 return QualType();
6287
6288 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6289 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6290 }
6291 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6292 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6293 }
Eli Friedman47f77112008-08-22 00:56:42 +00006294 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006295 }
6296
6297 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006298
Eli Friedmandcca6332009-06-01 01:22:52 +00006299 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6300 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006301
Chris Lattnerfd652912008-01-14 05:45:46 +00006302 // We want to consider the two function types to be the same for these
6303 // comparisons, just force one to the other.
6304 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6305 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006306
6307 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006308 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6309 LHSClass = Type::ConstantArray;
6310 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6311 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006312
John McCall8b07ec22010-05-15 11:32:37 +00006313 // ObjCInterfaces are just specialized ObjCObjects.
6314 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6315 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6316
Nate Begemance4d7fc2008-04-18 23:10:10 +00006317 // Canonicalize ExtVector -> Vector.
6318 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6319 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006320
Chris Lattner95554662008-04-07 05:43:21 +00006321 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006322 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006323 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006324 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006325 // Compatibility is based on the underlying type, not the promotion
6326 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006327 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006328 QualType TINT = ETy->getDecl()->getIntegerType();
6329 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006330 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006331 }
John McCall9dd450b2009-09-21 23:43:11 +00006332 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006333 QualType TINT = ETy->getDecl()->getIntegerType();
6334 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006335 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006336 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006337 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006338 if (OfBlockPointer && !BlockReturnType) {
6339 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6340 return LHS;
6341 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6342 return RHS;
6343 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006344
Eli Friedman47f77112008-08-22 00:56:42 +00006345 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006346 }
Eli Friedman47f77112008-08-22 00:56:42 +00006347
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006348 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006349 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006350#define TYPE(Class, Base)
6351#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006352#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006353#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6354#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6355#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006356 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006357
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006358 case Type::LValueReference:
6359 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006360 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006361 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006362
John McCall8b07ec22010-05-15 11:32:37 +00006363 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006364 case Type::IncompleteArray:
6365 case Type::VariableArray:
6366 case Type::FunctionProto:
6367 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006368 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006369
Chris Lattnerfd652912008-01-14 05:45:46 +00006370 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006371 {
6372 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006373 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6374 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006375 if (Unqualified) {
6376 LHSPointee = LHSPointee.getUnqualifiedType();
6377 RHSPointee = RHSPointee.getUnqualifiedType();
6378 }
6379 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6380 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006381 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006382 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006383 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006384 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006385 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006386 return getPointerType(ResultType);
6387 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006388 case Type::BlockPointer:
6389 {
6390 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006391 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6392 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006393 if (Unqualified) {
6394 LHSPointee = LHSPointee.getUnqualifiedType();
6395 RHSPointee = RHSPointee.getUnqualifiedType();
6396 }
6397 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6398 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006399 if (ResultType.isNull()) return QualType();
6400 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6401 return LHS;
6402 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6403 return RHS;
6404 return getBlockPointerType(ResultType);
6405 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006406 case Type::Atomic:
6407 {
6408 // Merge two pointer types, while trying to preserve typedef info
6409 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6410 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6411 if (Unqualified) {
6412 LHSValue = LHSValue.getUnqualifiedType();
6413 RHSValue = RHSValue.getUnqualifiedType();
6414 }
6415 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6416 Unqualified);
6417 if (ResultType.isNull()) return QualType();
6418 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6419 return LHS;
6420 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6421 return RHS;
6422 return getAtomicType(ResultType);
6423 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006424 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006425 {
6426 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6427 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6428 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6429 return QualType();
6430
6431 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6432 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006433 if (Unqualified) {
6434 LHSElem = LHSElem.getUnqualifiedType();
6435 RHSElem = RHSElem.getUnqualifiedType();
6436 }
6437
6438 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006439 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006440 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6441 return LHS;
6442 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6443 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006444 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6445 ArrayType::ArraySizeModifier(), 0);
6446 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6447 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006448 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6449 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006450 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6451 return LHS;
6452 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6453 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006454 if (LVAT) {
6455 // FIXME: This isn't correct! But tricky to implement because
6456 // the array's size has to be the size of LHS, but the type
6457 // has to be different.
6458 return LHS;
6459 }
6460 if (RVAT) {
6461 // FIXME: This isn't correct! But tricky to implement because
6462 // the array's size has to be the size of RHS, but the type
6463 // has to be different.
6464 return RHS;
6465 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006466 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6467 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006468 return getIncompleteArrayType(ResultType,
6469 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006470 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006471 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006472 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006473 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006474 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006475 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006476 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006477 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006478 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006479 case Type::Complex:
6480 // Distinct complex types are incompatible.
6481 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006482 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006483 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006484 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6485 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006486 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006487 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006488 case Type::ObjCObject: {
6489 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006490 // FIXME: This should be type compatibility, e.g. whether
6491 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006492 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6493 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6494 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006495 return LHS;
6496
Eli Friedman47f77112008-08-22 00:56:42 +00006497 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006498 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006499 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006500 if (OfBlockPointer) {
6501 if (canAssignObjCInterfacesInBlockPointer(
6502 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006503 RHS->getAs<ObjCObjectPointerType>(),
6504 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006505 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006506 return QualType();
6507 }
John McCall9dd450b2009-09-21 23:43:11 +00006508 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6509 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006510 return LHS;
6511
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006512 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006513 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006514 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006515
David Blaikie8a40f702012-01-17 06:56:22 +00006516 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006517}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006518
Fariborz Jahanian97676972011-09-28 21:52:05 +00006519bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6520 const FunctionProtoType *FromFunctionType,
6521 const FunctionProtoType *ToFunctionType) {
6522 if (FromFunctionType->hasAnyConsumedArgs() !=
6523 ToFunctionType->hasAnyConsumedArgs())
6524 return false;
6525 FunctionProtoType::ExtProtoInfo FromEPI =
6526 FromFunctionType->getExtProtoInfo();
6527 FunctionProtoType::ExtProtoInfo ToEPI =
6528 ToFunctionType->getExtProtoInfo();
6529 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6530 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6531 ArgIdx != NumArgs; ++ArgIdx) {
6532 if (FromEPI.ConsumedArguments[ArgIdx] !=
6533 ToEPI.ConsumedArguments[ArgIdx])
6534 return false;
6535 }
6536 return true;
6537}
6538
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006539/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6540/// 'RHS' attributes and returns the merged version; including for function
6541/// return types.
6542QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6543 QualType LHSCan = getCanonicalType(LHS),
6544 RHSCan = getCanonicalType(RHS);
6545 // If two types are identical, they are compatible.
6546 if (LHSCan == RHSCan)
6547 return LHS;
6548 if (RHSCan->isFunctionType()) {
6549 if (!LHSCan->isFunctionType())
6550 return QualType();
6551 QualType OldReturnType =
6552 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6553 QualType NewReturnType =
6554 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6555 QualType ResReturnType =
6556 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6557 if (ResReturnType.isNull())
6558 return QualType();
6559 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6560 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6561 // In either case, use OldReturnType to build the new function type.
6562 const FunctionType *F = LHS->getAs<FunctionType>();
6563 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006564 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6565 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006566 QualType ResultType
6567 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006568 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006569 return ResultType;
6570 }
6571 }
6572 return QualType();
6573 }
6574
6575 // If the qualifiers are different, the types can still be merged.
6576 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6577 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6578 if (LQuals != RQuals) {
6579 // If any of these qualifiers are different, we have a type mismatch.
6580 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6581 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6582 return QualType();
6583
6584 // Exactly one GC qualifier difference is allowed: __strong is
6585 // okay if the other type has no GC qualifier but is an Objective
6586 // C object pointer (i.e. implicitly strong by default). We fix
6587 // this by pretending that the unqualified type was actually
6588 // qualified __strong.
6589 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6590 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6591 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6592
6593 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6594 return QualType();
6595
6596 if (GC_L == Qualifiers::Strong)
6597 return LHS;
6598 if (GC_R == Qualifiers::Strong)
6599 return RHS;
6600 return QualType();
6601 }
6602
6603 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6604 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6605 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6606 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6607 if (ResQT == LHSBaseQT)
6608 return LHS;
6609 if (ResQT == RHSBaseQT)
6610 return RHS;
6611 }
6612 return QualType();
6613}
6614
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006615//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006616// Integer Predicates
6617//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006618
Jay Foad39c79802011-01-12 09:06:06 +00006619unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006620 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006621 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006622 if (T->isBooleanType())
6623 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006624 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006625 return (unsigned)getTypeSize(T);
6626}
6627
6628QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006629 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006630
6631 // Turn <4 x signed int> -> <4 x unsigned int>
6632 if (const VectorType *VTy = T->getAs<VectorType>())
6633 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006634 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006635
6636 // For enums, we return the unsigned version of the base type.
6637 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006638 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006639
6640 const BuiltinType *BTy = T->getAs<BuiltinType>();
6641 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006642 switch (BTy->getKind()) {
6643 case BuiltinType::Char_S:
6644 case BuiltinType::SChar:
6645 return UnsignedCharTy;
6646 case BuiltinType::Short:
6647 return UnsignedShortTy;
6648 case BuiltinType::Int:
6649 return UnsignedIntTy;
6650 case BuiltinType::Long:
6651 return UnsignedLongTy;
6652 case BuiltinType::LongLong:
6653 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006654 case BuiltinType::Int128:
6655 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006656 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006657 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006658 }
6659}
6660
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006661ASTMutationListener::~ASTMutationListener() { }
6662
Chris Lattnerecd79c62009-06-14 00:45:47 +00006663
6664//===----------------------------------------------------------------------===//
6665// Builtin Type Computation
6666//===----------------------------------------------------------------------===//
6667
6668/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006669/// pointer over the consumed characters. This returns the resultant type. If
6670/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6671/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6672/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006673///
6674/// RequiresICE is filled in on return to indicate whether the value is required
6675/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006676static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006677 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006678 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006679 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006680 // Modifiers.
6681 int HowLong = 0;
6682 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006683 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006684
Chris Lattnerdc226c22010-10-01 22:42:38 +00006685 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006686 bool Done = false;
6687 while (!Done) {
6688 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006689 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006690 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006691 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006692 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006693 case 'S':
6694 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6695 assert(!Signed && "Can't use 'S' modifier multiple times!");
6696 Signed = true;
6697 break;
6698 case 'U':
6699 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6700 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6701 Unsigned = true;
6702 break;
6703 case 'L':
6704 assert(HowLong <= 2 && "Can't have LLLL modifier");
6705 ++HowLong;
6706 break;
6707 }
6708 }
6709
6710 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006711
Chris Lattnerecd79c62009-06-14 00:45:47 +00006712 // Read the base type.
6713 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006714 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006715 case 'v':
6716 assert(HowLong == 0 && !Signed && !Unsigned &&
6717 "Bad modifiers used with 'v'!");
6718 Type = Context.VoidTy;
6719 break;
6720 case 'f':
6721 assert(HowLong == 0 && !Signed && !Unsigned &&
6722 "Bad modifiers used with 'f'!");
6723 Type = Context.FloatTy;
6724 break;
6725 case 'd':
6726 assert(HowLong < 2 && !Signed && !Unsigned &&
6727 "Bad modifiers used with 'd'!");
6728 if (HowLong)
6729 Type = Context.LongDoubleTy;
6730 else
6731 Type = Context.DoubleTy;
6732 break;
6733 case 's':
6734 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6735 if (Unsigned)
6736 Type = Context.UnsignedShortTy;
6737 else
6738 Type = Context.ShortTy;
6739 break;
6740 case 'i':
6741 if (HowLong == 3)
6742 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6743 else if (HowLong == 2)
6744 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6745 else if (HowLong == 1)
6746 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6747 else
6748 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6749 break;
6750 case 'c':
6751 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6752 if (Signed)
6753 Type = Context.SignedCharTy;
6754 else if (Unsigned)
6755 Type = Context.UnsignedCharTy;
6756 else
6757 Type = Context.CharTy;
6758 break;
6759 case 'b': // boolean
6760 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6761 Type = Context.BoolTy;
6762 break;
6763 case 'z': // size_t.
6764 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6765 Type = Context.getSizeType();
6766 break;
6767 case 'F':
6768 Type = Context.getCFConstantStringType();
6769 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006770 case 'G':
6771 Type = Context.getObjCIdType();
6772 break;
6773 case 'H':
6774 Type = Context.getObjCSelType();
6775 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006776 case 'a':
6777 Type = Context.getBuiltinVaListType();
6778 assert(!Type.isNull() && "builtin va list type not initialized!");
6779 break;
6780 case 'A':
6781 // This is a "reference" to a va_list; however, what exactly
6782 // this means depends on how va_list is defined. There are two
6783 // different kinds of va_list: ones passed by value, and ones
6784 // passed by reference. An example of a by-value va_list is
6785 // x86, where va_list is a char*. An example of by-ref va_list
6786 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6787 // we want this argument to be a char*&; for x86-64, we want
6788 // it to be a __va_list_tag*.
6789 Type = Context.getBuiltinVaListType();
6790 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006791 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006792 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006793 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006794 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006795 break;
6796 case 'V': {
6797 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006798 unsigned NumElements = strtoul(Str, &End, 10);
6799 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006800 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006801
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006802 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6803 RequiresICE, false);
6804 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006805
6806 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006807 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006808 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006809 break;
6810 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006811 case 'E': {
6812 char *End;
6813
6814 unsigned NumElements = strtoul(Str, &End, 10);
6815 assert(End != Str && "Missing vector size");
6816
6817 Str = End;
6818
6819 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6820 false);
6821 Type = Context.getExtVectorType(ElementType, NumElements);
6822 break;
6823 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006824 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006825 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6826 false);
6827 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006828 Type = Context.getComplexType(ElementType);
6829 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006830 }
6831 case 'Y' : {
6832 Type = Context.getPointerDiffType();
6833 break;
6834 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006835 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006836 Type = Context.getFILEType();
6837 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006838 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006839 return QualType();
6840 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006841 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006842 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006843 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006844 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006845 else
6846 Type = Context.getjmp_bufType();
6847
Mike Stump2adb4da2009-07-28 23:47:15 +00006848 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006849 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006850 return QualType();
6851 }
6852 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006853 case 'K':
6854 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6855 Type = Context.getucontext_tType();
6856
6857 if (Type.isNull()) {
6858 Error = ASTContext::GE_Missing_ucontext;
6859 return QualType();
6860 }
6861 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006862 }
Mike Stump11289f42009-09-09 15:08:12 +00006863
Chris Lattnerdc226c22010-10-01 22:42:38 +00006864 // If there are modifiers and if we're allowed to parse them, go for it.
6865 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006866 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006867 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006868 default: Done = true; --Str; break;
6869 case '*':
6870 case '&': {
6871 // Both pointers and references can have their pointee types
6872 // qualified with an address space.
6873 char *End;
6874 unsigned AddrSpace = strtoul(Str, &End, 10);
6875 if (End != Str && AddrSpace != 0) {
6876 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6877 Str = End;
6878 }
6879 if (c == '*')
6880 Type = Context.getPointerType(Type);
6881 else
6882 Type = Context.getLValueReferenceType(Type);
6883 break;
6884 }
6885 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6886 case 'C':
6887 Type = Type.withConst();
6888 break;
6889 case 'D':
6890 Type = Context.getVolatileType(Type);
6891 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006892 case 'R':
6893 Type = Type.withRestrict();
6894 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006895 }
6896 }
Chris Lattner84733392010-10-01 07:13:18 +00006897
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006898 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006899 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006900
Chris Lattnerecd79c62009-06-14 00:45:47 +00006901 return Type;
6902}
6903
6904/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006905QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006906 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006907 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006908 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006909
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006910 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006911
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006912 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006913 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006914 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6915 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006916 if (Error != GE_None)
6917 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006918
6919 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6920
Chris Lattnerecd79c62009-06-14 00:45:47 +00006921 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006922 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006923 if (Error != GE_None)
6924 return QualType();
6925
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006926 // If this argument is required to be an IntegerConstantExpression and the
6927 // caller cares, fill in the bitmask we return.
6928 if (RequiresICE && IntegerConstantArgs)
6929 *IntegerConstantArgs |= 1 << ArgTypes.size();
6930
Chris Lattnerecd79c62009-06-14 00:45:47 +00006931 // Do array -> pointer decay. The builtin should use the decayed type.
6932 if (Ty->isArrayType())
6933 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006934
Chris Lattnerecd79c62009-06-14 00:45:47 +00006935 ArgTypes.push_back(Ty);
6936 }
6937
6938 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6939 "'.' should only occur at end of builtin type list!");
6940
John McCall991eb4b2010-12-21 00:44:39 +00006941 FunctionType::ExtInfo EI;
6942 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6943
6944 bool Variadic = (TypeStr[0] == '.');
6945
6946 // We really shouldn't be making a no-proto type here, especially in C++.
6947 if (ArgTypes.empty() && Variadic)
6948 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006949
John McCalldb40c7f2010-12-14 08:05:40 +00006950 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006951 EPI.ExtInfo = EI;
6952 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006953
6954 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006955}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006956
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006957GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6958 GVALinkage External = GVA_StrongExternal;
6959
6960 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006961 switch (L) {
6962 case NoLinkage:
6963 case InternalLinkage:
6964 case UniqueExternalLinkage:
6965 return GVA_Internal;
6966
6967 case ExternalLinkage:
6968 switch (FD->getTemplateSpecializationKind()) {
6969 case TSK_Undeclared:
6970 case TSK_ExplicitSpecialization:
6971 External = GVA_StrongExternal;
6972 break;
6973
6974 case TSK_ExplicitInstantiationDefinition:
6975 return GVA_ExplicitTemplateInstantiation;
6976
6977 case TSK_ExplicitInstantiationDeclaration:
6978 case TSK_ImplicitInstantiation:
6979 External = GVA_TemplateInstantiation;
6980 break;
6981 }
6982 }
6983
6984 if (!FD->isInlined())
6985 return External;
6986
David Blaikiebbafb8a2012-03-11 07:00:24 +00006987 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006988 // GNU or C99 inline semantics. Determine whether this symbol should be
6989 // externally visible.
6990 if (FD->isInlineDefinitionExternallyVisible())
6991 return External;
6992
6993 // C99 inline semantics, where the symbol is not externally visible.
6994 return GVA_C99Inline;
6995 }
6996
6997 // C++0x [temp.explicit]p9:
6998 // [ Note: The intent is that an inline function that is the subject of
6999 // an explicit instantiation declaration will still be implicitly
7000 // instantiated when used so that the body can be considered for
7001 // inlining, but that no out-of-line copy of the inline function would be
7002 // generated in the translation unit. -- end note ]
7003 if (FD->getTemplateSpecializationKind()
7004 == TSK_ExplicitInstantiationDeclaration)
7005 return GVA_C99Inline;
7006
7007 return GVA_CXXInline;
7008}
7009
7010GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7011 // If this is a static data member, compute the kind of template
7012 // specialization. Otherwise, this variable is not part of a
7013 // template.
7014 TemplateSpecializationKind TSK = TSK_Undeclared;
7015 if (VD->isStaticDataMember())
7016 TSK = VD->getTemplateSpecializationKind();
7017
7018 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007019 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007020 VD->getType()->getLinkage() == UniqueExternalLinkage)
7021 L = UniqueExternalLinkage;
7022
7023 switch (L) {
7024 case NoLinkage:
7025 case InternalLinkage:
7026 case UniqueExternalLinkage:
7027 return GVA_Internal;
7028
7029 case ExternalLinkage:
7030 switch (TSK) {
7031 case TSK_Undeclared:
7032 case TSK_ExplicitSpecialization:
7033 return GVA_StrongExternal;
7034
7035 case TSK_ExplicitInstantiationDeclaration:
7036 llvm_unreachable("Variable should not be instantiated");
7037 // Fall through to treat this like any other instantiation.
7038
7039 case TSK_ExplicitInstantiationDefinition:
7040 return GVA_ExplicitTemplateInstantiation;
7041
7042 case TSK_ImplicitInstantiation:
7043 return GVA_TemplateInstantiation;
7044 }
7045 }
7046
David Blaikie8a40f702012-01-17 06:56:22 +00007047 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007048}
7049
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007050bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007051 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7052 if (!VD->isFileVarDecl())
7053 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007054 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007055 return false;
7056
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007057 // Weak references don't produce any output by themselves.
7058 if (D->hasAttr<WeakRefAttr>())
7059 return false;
7060
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007061 // Aliases and used decls are required.
7062 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7063 return true;
7064
7065 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7066 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007067 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007068 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007069
7070 // Constructors and destructors are required.
7071 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7072 return true;
7073
7074 // The key function for a class is required.
7075 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7076 const CXXRecordDecl *RD = MD->getParent();
7077 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7078 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7079 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7080 return true;
7081 }
7082 }
7083
7084 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7085
7086 // static, static inline, always_inline, and extern inline functions can
7087 // always be deferred. Normal inline functions can be deferred in C99/C++.
7088 // Implicit template instantiations can also be deferred in C++.
7089 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007090 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007091 return false;
7092 return true;
7093 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007094
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007095 const VarDecl *VD = cast<VarDecl>(D);
7096 assert(VD->isFileVarDecl() && "Expected file scoped var");
7097
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007098 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7099 return false;
7100
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007101 // Structs that have non-trivial constructors or destructors are required.
7102
7103 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007104 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007105 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7106 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007107 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7108 RD->hasTrivialCopyConstructor() &&
7109 RD->hasTrivialMoveConstructor() &&
7110 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007111 return true;
7112 }
7113 }
7114
7115 GVALinkage L = GetGVALinkageForVariable(VD);
7116 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7117 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7118 return false;
7119 }
7120
7121 return true;
7122}
Charles Davis53c59df2010-08-16 03:33:14 +00007123
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007124CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007125 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007126 return ABI->getDefaultMethodCallConv(isVariadic);
7127}
7128
7129CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7130 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7131 return CC_Default;
7132 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007133}
7134
Jay Foad39c79802011-01-12 09:06:06 +00007135bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007136 // Pass through to the C++ ABI object
7137 return ABI->isNearlyEmpty(RD);
7138}
7139
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007140MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007141 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007142 case CXXABI_ARM:
7143 case CXXABI_Itanium:
7144 return createItaniumMangleContext(*this, getDiagnostics());
7145 case CXXABI_Microsoft:
7146 return createMicrosoftMangleContext(*this, getDiagnostics());
7147 }
David Blaikie83d382b2011-09-23 05:06:16 +00007148 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007149}
7150
Charles Davis53c59df2010-08-16 03:33:14 +00007151CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007152
7153size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007154 return ASTRecordLayouts.getMemorySize()
7155 + llvm::capacity_in_bytes(ObjCLayouts)
7156 + llvm::capacity_in_bytes(KeyFunctions)
7157 + llvm::capacity_in_bytes(ObjCImpls)
7158 + llvm::capacity_in_bytes(BlockVarCopyInits)
7159 + llvm::capacity_in_bytes(DeclAttrs)
7160 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7161 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7162 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7163 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7164 + llvm::capacity_in_bytes(OverriddenMethods)
7165 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007166 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007167 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007168}
Ted Kremenek540017e2011-10-06 05:00:56 +00007169
Douglas Gregor63798542012-02-20 19:44:39 +00007170unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7171 CXXRecordDecl *Lambda = CallOperator->getParent();
7172 return LambdaMangleContexts[Lambda->getDeclContext()]
7173 .getManglingNumber(CallOperator);
7174}
7175
7176
Ted Kremenek540017e2011-10-06 05:00:56 +00007177void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7178 ParamIndices[D] = index;
7179}
7180
7181unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7182 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7183 assert(I != ParamIndices.end() &&
7184 "ParmIndices lacks entry set by ParmVarDecl");
7185 return I->second;
7186}