blob: 99c5ff6d5673a5bbcd4a68a6750d5c40728b28b9 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoec925312012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000037#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000059const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
60 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
75 ArrayRef<RawComment> RawComments = Comments.getComments();
76
77 // If there are no comments anywhere, we won't find anything.
78 if (RawComments.empty())
79 return NULL;
80
81 // If the declaration doesn't map directly to a location in a file, we
82 // can't find the comment.
83 SourceLocation DeclLoc = D->getLocation();
84 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
85 return NULL;
86
87 // Find the comment that occurs just after this declaration.
88 ArrayRef<RawComment>::iterator Comment
89 = std::lower_bound(RawComments.begin(),
90 RawComments.end(),
Dmitri Gribenkofecc2e02012-06-21 21:02:45 +000091 RawComment(SourceMgr, SourceRange(DeclLoc)),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000092 BeforeThanCompare<RawComment>(SourceMgr));
93
94 // Decompose the location for the declaration and find the beginning of the
95 // file buffer.
96 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
97
98 // First check whether we have a trailing comment.
99 if (Comment != RawComments.end() &&
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000100 Comment->isDocumentation() && Comment->isTrailingComment() &&
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000101 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
102 std::pair<FileID, unsigned> CommentBeginDecomp
103 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
104 // Check that Doxygen trailing comment comes after the declaration, starts
105 // on the same line and in the same file as the declaration.
106 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
107 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
108 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
109 CommentBeginDecomp.second)) {
110 return &*Comment;
111 }
112 }
113
114 // The comment just after the declaration was not a trailing comment.
115 // Let's look at the previous comment.
116 if (Comment == RawComments.begin())
117 return NULL;
118 --Comment;
119
120 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000121 if (!Comment->isDocumentation() || Comment->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000122 return NULL;
123
124 // Decompose the end of the comment.
125 std::pair<FileID, unsigned> CommentEndDecomp
126 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
127
128 // If the comment and the declaration aren't in the same file, then they
129 // aren't related.
130 if (DeclLocDecomp.first != CommentEndDecomp.first)
131 return NULL;
132
133 // Get the corresponding buffer.
134 bool Invalid = false;
135 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
136 &Invalid).data();
137 if (Invalid)
138 return NULL;
139
140 // Extract text between the comment and declaration.
141 StringRef Text(Buffer + CommentEndDecomp.second,
142 DeclLocDecomp.second - CommentEndDecomp.second);
143
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000144 // There should be no other declarations or preprocessor directives between
145 // comment and declaration.
146 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 return NULL;
148
149 return &*Comment;
150}
151
152const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
153 // Check whether we have cached a comment string for this declaration
154 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000155 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000156 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000157 if (Pos != DeclComments.end()) {
158 RawAndParsedComment C = Pos->second;
159 return C.first;
160 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000161
162 const RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000163 // If we found a comment, it should be a documentation comment.
164 assert(!RC || RC->isDocumentation());
Dmitri Gribenko08630052012-07-06 15:40:08 +0000165 DeclComments[D] =
166 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 return RC;
168}
169
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000170comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
171 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
172 = DeclComments.find(D);
173 const RawComment *RC;
174 if (Pos != DeclComments.end()) {
175 RawAndParsedComment C = Pos->second;
176 if (comments::FullComment *FC = C.second)
177 return FC;
178 RC = C.first;
179 } else
180 RC = getRawCommentForDecl(D);
181
182 if (!RC)
183 return NULL;
184
185 const StringRef RawText = RC->getRawText(SourceMgr);
186 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
187 RawText.begin(), RawText.end());
188
189 comments::Sema S(this->BumpAlloc);
190 comments::Parser P(L, S, this->BumpAlloc);
191
192 comments::FullComment *FC = P.parseFullComment();
193 DeclComments[D].second = FC;
194 return FC;
195}
196
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000197void
198ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
199 TemplateTemplateParmDecl *Parm) {
200 ID.AddInteger(Parm->getDepth());
201 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000202 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000203
204 TemplateParameterList *Params = Parm->getTemplateParameters();
205 ID.AddInteger(Params->size());
206 for (TemplateParameterList::const_iterator P = Params->begin(),
207 PEnd = Params->end();
208 P != PEnd; ++P) {
209 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
210 ID.AddInteger(0);
211 ID.AddBoolean(TTP->isParameterPack());
212 continue;
213 }
214
215 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
216 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000217 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000218 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000219 if (NTTP->isExpandedParameterPack()) {
220 ID.AddBoolean(true);
221 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000222 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
223 QualType T = NTTP->getExpansionType(I);
224 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
225 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000226 } else
227 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000228 continue;
229 }
230
231 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
232 ID.AddInteger(2);
233 Profile(ID, TTP);
234 }
235}
236
237TemplateTemplateParmDecl *
238ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000239 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000240 // Check if we already have a canonical template template parameter.
241 llvm::FoldingSetNodeID ID;
242 CanonicalTemplateTemplateParm::Profile(ID, TTP);
243 void *InsertPos = 0;
244 CanonicalTemplateTemplateParm *Canonical
245 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
246 if (Canonical)
247 return Canonical->getParam();
248
249 // Build a canonical template parameter list.
250 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000251 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000252 CanonParams.reserve(Params->size());
253 for (TemplateParameterList::const_iterator P = Params->begin(),
254 PEnd = Params->end();
255 P != PEnd; ++P) {
256 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
257 CanonParams.push_back(
258 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000259 SourceLocation(),
260 SourceLocation(),
261 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000262 TTP->getIndex(), 0, false,
263 TTP->isParameterPack()));
264 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000265 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
266 QualType T = getCanonicalType(NTTP->getType());
267 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
268 NonTypeTemplateParmDecl *Param;
269 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000270 SmallVector<QualType, 2> ExpandedTypes;
271 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000272 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
273 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
274 ExpandedTInfos.push_back(
275 getTrivialTypeSourceInfo(ExpandedTypes.back()));
276 }
277
278 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000279 SourceLocation(),
280 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000281 NTTP->getDepth(),
282 NTTP->getPosition(), 0,
283 T,
284 TInfo,
285 ExpandedTypes.data(),
286 ExpandedTypes.size(),
287 ExpandedTInfos.data());
288 } else {
289 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000290 SourceLocation(),
291 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000292 NTTP->getDepth(),
293 NTTP->getPosition(), 0,
294 T,
295 NTTP->isParameterPack(),
296 TInfo);
297 }
298 CanonParams.push_back(Param);
299
300 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000301 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
302 cast<TemplateTemplateParmDecl>(*P)));
303 }
304
305 TemplateTemplateParmDecl *CanonTTP
306 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
307 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000308 TTP->getPosition(),
309 TTP->isParameterPack(),
310 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000311 TemplateParameterList::Create(*this, SourceLocation(),
312 SourceLocation(),
313 CanonParams.data(),
314 CanonParams.size(),
315 SourceLocation()));
316
317 // Get the new insert position for the node we care about.
318 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
319 assert(Canonical == 0 && "Shouldn't be in the map!");
320 (void)Canonical;
321
322 // Create the canonical template template parameter entry.
323 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
324 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
325 return CanonTTP;
326}
327
Charles Davis53c59df2010-08-16 03:33:14 +0000328CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000329 if (!LangOpts.CPlusPlus) return 0;
330
Charles Davis6bcb07a2010-08-19 02:18:14 +0000331 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000332 case CXXABI_ARM:
333 return CreateARMCXXABI(*this);
334 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000335 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000336 case CXXABI_Microsoft:
337 return CreateMicrosoftCXXABI(*this);
338 }
David Blaikie8a40f702012-01-17 06:56:22 +0000339 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000340}
341
Douglas Gregore8bbc122011-09-02 00:18:52 +0000342static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000343 const LangOptions &LOpts) {
344 if (LOpts.FakeAddressSpaceMap) {
345 // The fake address space map must have a distinct entry for each
346 // language-specific address space.
347 static const unsigned FakeAddrSpaceMap[] = {
348 1, // opencl_global
349 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000350 3, // opencl_constant
351 4, // cuda_device
352 5, // cuda_constant
353 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000354 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000355 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000356 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000357 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000358 }
359}
360
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000361ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000362 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000363 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000364 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000365 unsigned size_reserve,
366 bool DelayInitialization)
367 : FunctionProtoTypes(this_()),
368 TemplateSpecializationTypes(this_()),
369 DependentTemplateSpecializationTypes(this_()),
370 SubstTemplateTemplateParmPacks(this_()),
371 GlobalNestedNameSpecifier(0),
372 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000373 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000374 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000375 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000376 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000377 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
378 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
379 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000380 NullTypeSourceInfo(QualType()),
381 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000382 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000383 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000384 Idents(idents), Selectors(sels),
385 BuiltinInfo(builtins),
386 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000387 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000388 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000389 LastSDM(0, 0),
390 UniqueBlockByRefTypeID(0)
391{
Mike Stump11289f42009-09-09 15:08:12 +0000392 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000393 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000394
395 if (!DelayInitialization) {
396 assert(t && "No target supplied for ASTContext initialization");
397 InitBuiltinTypes(*t);
398 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000399}
400
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000401ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000402 // Release the DenseMaps associated with DeclContext objects.
403 // FIXME: Is this the ideal solution?
404 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000405
Douglas Gregor5b11d492010-07-25 17:53:33 +0000406 // Call all of the deallocation functions.
407 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
408 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000409
Ted Kremenek076baeb2010-06-08 23:00:58 +0000410 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000411 // because they can contain DenseMaps.
412 for (llvm::DenseMap<const ObjCContainerDecl*,
413 const ASTRecordLayout*>::iterator
414 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
415 // Increment in loop to prevent using deallocated memory.
416 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
417 R->Destroy(*this);
418
Ted Kremenek076baeb2010-06-08 23:00:58 +0000419 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
420 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
421 // Increment in loop to prevent using deallocated memory.
422 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
423 R->Destroy(*this);
424 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000425
426 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
427 AEnd = DeclAttrs.end();
428 A != AEnd; ++A)
429 A->second->~AttrVec();
430}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000431
Douglas Gregor1a809332010-05-23 18:26:36 +0000432void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
433 Deallocations.push_back(std::make_pair(Callback, Data));
434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000437ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000438 ExternalSource.reset(Source.take());
439}
440
Chris Lattner4eb445d2007-01-26 01:27:23 +0000441void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000442 llvm::errs() << "\n*** AST Context Stats:\n";
443 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000444
Douglas Gregora30d0462009-05-26 14:40:08 +0000445 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000446#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000447#define ABSTRACT_TYPE(Name, Parent)
448#include "clang/AST/TypeNodes.def"
449 0 // Extra
450 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000451
Chris Lattner4eb445d2007-01-26 01:27:23 +0000452 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
453 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000454 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000455 }
456
Douglas Gregora30d0462009-05-26 14:40:08 +0000457 unsigned Idx = 0;
458 unsigned TotalBytes = 0;
459#define TYPE(Name, Parent) \
460 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000461 llvm::errs() << " " << counts[Idx] << " " << #Name \
462 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000463 TotalBytes += counts[Idx] * sizeof(Name##Type); \
464 ++Idx;
465#define ABSTRACT_TYPE(Name, Parent)
466#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000467
Chandler Carruth3c147a72011-07-04 05:32:14 +0000468 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
469
Douglas Gregor7454c562010-07-02 20:37:36 +0000470 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000471 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
472 << NumImplicitDefaultConstructors
473 << " implicit default constructors created\n";
474 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
475 << NumImplicitCopyConstructors
476 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000477 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000478 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
479 << NumImplicitMoveConstructors
480 << " implicit move constructors created\n";
481 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
482 << NumImplicitCopyAssignmentOperators
483 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000484 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000485 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
486 << NumImplicitMoveAssignmentOperators
487 << " implicit move assignment operators created\n";
488 llvm::errs() << NumImplicitDestructorsDeclared << "/"
489 << NumImplicitDestructors
490 << " implicit destructors created\n";
491
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000492 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000493 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000494 ExternalSource->PrintStats();
495 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000496
Douglas Gregor5b11d492010-07-25 17:53:33 +0000497 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000498}
499
Douglas Gregor801c99d2011-08-12 06:49:56 +0000500TypedefDecl *ASTContext::getInt128Decl() const {
501 if (!Int128Decl) {
502 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
503 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
504 getTranslationUnitDecl(),
505 SourceLocation(),
506 SourceLocation(),
507 &Idents.get("__int128_t"),
508 TInfo);
509 }
510
511 return Int128Decl;
512}
513
514TypedefDecl *ASTContext::getUInt128Decl() const {
515 if (!UInt128Decl) {
516 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
517 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
518 getTranslationUnitDecl(),
519 SourceLocation(),
520 SourceLocation(),
521 &Idents.get("__uint128_t"),
522 TInfo);
523 }
524
525 return UInt128Decl;
526}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000527
John McCall48f2d582009-10-23 23:03:21 +0000528void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000529 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000530 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000531 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000532}
533
Douglas Gregore8bbc122011-09-02 00:18:52 +0000534void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
535 assert((!this->Target || this->Target == &Target) &&
536 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000537 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000538
Douglas Gregore8bbc122011-09-02 00:18:52 +0000539 this->Target = &Target;
540
541 ABI.reset(createCXXABI(Target));
542 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
543
Chris Lattner970e54e2006-11-12 00:37:36 +0000544 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000545 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattner970e54e2006-11-12 00:37:36 +0000547 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000548 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000549 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000550 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000551 InitBuiltinType(CharTy, BuiltinType::Char_S);
552 else
553 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000554 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000555 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
556 InitBuiltinType(ShortTy, BuiltinType::Short);
557 InitBuiltinType(IntTy, BuiltinType::Int);
558 InitBuiltinType(LongTy, BuiltinType::Long);
559 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattner970e54e2006-11-12 00:37:36 +0000561 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000562 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
563 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
564 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
565 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
566 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattner970e54e2006-11-12 00:37:36 +0000568 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000569 InitBuiltinType(FloatTy, BuiltinType::Float);
570 InitBuiltinType(DoubleTy, BuiltinType::Double);
571 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000572
Chris Lattnerf122cef2009-04-30 02:43:43 +0000573 // GNU extension, 128-bit integers.
574 InitBuiltinType(Int128Ty, BuiltinType::Int128);
575 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
576
Chris Lattnerad3467e2010-12-25 23:25:43 +0000577 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000578 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000579 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
580 else // -fshort-wchar makes wchar_t be unsigned.
581 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
582 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000583 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000584
James Molloy36365542012-05-04 10:55:22 +0000585 WIntTy = getFromTargetType(Target.getWIntType());
586
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000587 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
588 InitBuiltinType(Char16Ty, BuiltinType::Char16);
589 else // C99
590 Char16Ty = getFromTargetType(Target.getChar16Type());
591
592 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
593 InitBuiltinType(Char32Ty, BuiltinType::Char32);
594 else // C99
595 Char32Ty = getFromTargetType(Target.getChar32Type());
596
Douglas Gregor4619e432008-12-05 23:32:09 +0000597 // Placeholder type for type-dependent expressions whose type is
598 // completely unknown. No code should ever check a type against
599 // DependentTy and users should never see it; however, it is here to
600 // help diagnose failures to properly check for type-dependent
601 // expressions.
602 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603
John McCall36e7fe32010-10-12 00:20:44 +0000604 // Placeholder type for functions.
605 InitBuiltinType(OverloadTy, BuiltinType::Overload);
606
John McCall0009fcc2011-04-26 20:42:42 +0000607 // Placeholder type for bound members.
608 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
609
John McCall526ab472011-10-25 17:37:35 +0000610 // Placeholder type for pseudo-objects.
611 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
612
John McCall31996342011-04-07 08:22:57 +0000613 // "any" type; useful for debugger-like clients.
614 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
615
John McCall8a6b59a2011-10-17 18:09:15 +0000616 // Placeholder type for unbridged ARC casts.
617 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
618
Chris Lattner970e54e2006-11-12 00:37:36 +0000619 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000620 FloatComplexTy = getComplexType(FloatTy);
621 DoubleComplexTy = getComplexType(DoubleTy);
622 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000623
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000624 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000625 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
626 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000627 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000628
629 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000630 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
631 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000632
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000633 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000634
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000635 // void * type
636 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000637
638 // nullptr type (C++0x 2.14.7)
639 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000640
641 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
642 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000643
644 // Builtin type used to help define __builtin_va_list.
645 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000646}
647
David Blaikie9c902b52011-09-25 23:23:43 +0000648DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000649 return SourceMgr.getDiagnostics();
650}
651
Douglas Gregor561eceb2010-08-30 16:49:28 +0000652AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
653 AttrVec *&Result = DeclAttrs[D];
654 if (!Result) {
655 void *Mem = Allocate(sizeof(AttrVec));
656 Result = new (Mem) AttrVec;
657 }
658
659 return *Result;
660}
661
662/// \brief Erase the attributes corresponding to the given declaration.
663void ASTContext::eraseDeclAttrs(const Decl *D) {
664 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
665 if (Pos != DeclAttrs.end()) {
666 Pos->second->~AttrVec();
667 DeclAttrs.erase(Pos);
668 }
669}
670
Douglas Gregor86d142a2009-10-08 07:24:58 +0000671MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000672ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000673 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000674 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000675 = InstantiatedFromStaticDataMember.find(Var);
676 if (Pos == InstantiatedFromStaticDataMember.end())
677 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000678
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000679 return Pos->second;
680}
681
Mike Stump11289f42009-09-09 15:08:12 +0000682void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000683ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000684 TemplateSpecializationKind TSK,
685 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000686 assert(Inst->isStaticDataMember() && "Not a static data member");
687 assert(Tmpl->isStaticDataMember() && "Not a static data member");
688 assert(!InstantiatedFromStaticDataMember[Inst] &&
689 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000690 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000691 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000692}
693
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000694FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
695 const FunctionDecl *FD){
696 assert(FD && "Specialization is 0");
697 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000698 = ClassScopeSpecializationPattern.find(FD);
699 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000700 return 0;
701
702 return Pos->second;
703}
704
705void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
706 FunctionDecl *Pattern) {
707 assert(FD && "Specialization is 0");
708 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000709 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000710}
711
John McCalle61f2ba2009-11-18 02:36:19 +0000712NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000713ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000714 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000715 = InstantiatedFromUsingDecl.find(UUD);
716 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000717 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000718
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000719 return Pos->second;
720}
721
722void
John McCallb96ec562009-12-04 22:46:56 +0000723ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
724 assert((isa<UsingDecl>(Pattern) ||
725 isa<UnresolvedUsingValueDecl>(Pattern) ||
726 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
727 "pattern decl is not a using decl");
728 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
729 InstantiatedFromUsingDecl[Inst] = Pattern;
730}
731
732UsingShadowDecl *
733ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
734 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
735 = InstantiatedFromUsingShadowDecl.find(Inst);
736 if (Pos == InstantiatedFromUsingShadowDecl.end())
737 return 0;
738
739 return Pos->second;
740}
741
742void
743ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
744 UsingShadowDecl *Pattern) {
745 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
746 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000747}
748
Anders Carlsson5da84842009-09-01 04:26:58 +0000749FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
750 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
751 = InstantiatedFromUnnamedFieldDecl.find(Field);
752 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
753 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000754
Anders Carlsson5da84842009-09-01 04:26:58 +0000755 return Pos->second;
756}
757
758void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
759 FieldDecl *Tmpl) {
760 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
761 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
762 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
763 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000764
Anders Carlsson5da84842009-09-01 04:26:58 +0000765 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
766}
767
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000768bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
769 const FieldDecl *LastFD) const {
770 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000771 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000772}
773
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000774bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
775 const FieldDecl *LastFD) const {
776 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000777 FD->getBitWidthValue(*this) == 0 &&
778 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000779}
780
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000781bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
782 const FieldDecl *LastFD) const {
783 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000784 FD->getBitWidthValue(*this) &&
785 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000786}
787
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000788bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000789 const FieldDecl *LastFD) const {
790 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000791 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000792}
793
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000794bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000795 const FieldDecl *LastFD) const {
796 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000797 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000798}
799
Douglas Gregor832940b2010-03-02 23:58:15 +0000800ASTContext::overridden_cxx_method_iterator
801ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
802 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
803 = OverriddenMethods.find(Method);
804 if (Pos == OverriddenMethods.end())
805 return 0;
806
807 return Pos->second.begin();
808}
809
810ASTContext::overridden_cxx_method_iterator
811ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
812 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
813 = OverriddenMethods.find(Method);
814 if (Pos == OverriddenMethods.end())
815 return 0;
816
817 return Pos->second.end();
818}
819
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000820unsigned
821ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
822 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
823 = OverriddenMethods.find(Method);
824 if (Pos == OverriddenMethods.end())
825 return 0;
826
827 return Pos->second.size();
828}
829
Douglas Gregor832940b2010-03-02 23:58:15 +0000830void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
831 const CXXMethodDecl *Overridden) {
832 OverriddenMethods[Method].push_back(Overridden);
833}
834
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000835void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
836 assert(!Import->NextLocalImport && "Import declaration already in the chain");
837 assert(!Import->isFromASTFile() && "Non-local import declaration");
838 if (!FirstLocalImport) {
839 FirstLocalImport = Import;
840 LastLocalImport = Import;
841 return;
842 }
843
844 LastLocalImport->NextLocalImport = Import;
845 LastLocalImport = Import;
846}
847
Chris Lattner53cfe802007-07-18 17:52:12 +0000848//===----------------------------------------------------------------------===//
849// Type Sizing and Analysis
850//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000851
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000852/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
853/// scalar floating point type.
854const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000855 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000856 assert(BT && "Not a floating point type!");
857 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000858 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000859 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000860 case BuiltinType::Float: return Target->getFloatFormat();
861 case BuiltinType::Double: return Target->getDoubleFormat();
862 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000863 }
864}
865
Ken Dyck160146e2010-01-27 17:10:57 +0000866/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000867/// specified decl. Note that bitfields do not have a valid alignment, so
868/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000869/// If @p RefAsPointee, references are treated like their underlying type
870/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000871CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000872 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000873
John McCall94268702010-10-08 18:24:19 +0000874 bool UseAlignAttrOnly = false;
875 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
876 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000877
John McCall94268702010-10-08 18:24:19 +0000878 // __attribute__((aligned)) can increase or decrease alignment
879 // *except* on a struct or struct member, where it only increases
880 // alignment unless 'packed' is also specified.
881 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000882 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000883 // ignore that possibility; Sema should diagnose it.
884 if (isa<FieldDecl>(D)) {
885 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
886 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
887 } else {
888 UseAlignAttrOnly = true;
889 }
890 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000891 else if (isa<FieldDecl>(D))
892 UseAlignAttrOnly =
893 D->hasAttr<PackedAttr>() ||
894 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000895
John McCall4e819612011-01-20 07:57:12 +0000896 // If we're using the align attribute only, just ignore everything
897 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000898 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000899 // do nothing
900
John McCall94268702010-10-08 18:24:19 +0000901 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000902 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000903 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000904 if (RefAsPointee)
905 T = RT->getPointeeType();
906 else
907 T = getPointerType(RT->getPointeeType());
908 }
909 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000910 // Adjust alignments of declarations with array type by the
911 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000912 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000913 const ArrayType *arrayType;
914 if (MinWidth && (arrayType = getAsArrayType(T))) {
915 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000916 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000917 else if (isa<ConstantArrayType>(arrayType) &&
918 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000919 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000920
John McCall33ddac02011-01-19 10:06:00 +0000921 // Walk through any array types while we're at it.
922 T = getBaseElementType(arrayType);
923 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000924 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000925 }
John McCall4e819612011-01-20 07:57:12 +0000926
927 // Fields can be subject to extra alignment constraints, like if
928 // the field is packed, the struct is packed, or the struct has a
929 // a max-field-alignment constraint (#pragma pack). So calculate
930 // the actual alignment of the field within the struct, and then
931 // (as we're expected to) constrain that by the alignment of the type.
932 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
933 // So calculate the alignment of the field.
934 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
935
936 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000937 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000938
939 // Use the GCD of that and the offset within the record.
940 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
941 if (offset > 0) {
942 // Alignment is always a power of 2, so the GCD will be a power of 2,
943 // which means we get to do this crazy thing instead of Euclid's.
944 uint64_t lowBitOfOffset = offset & (~offset + 1);
945 if (lowBitOfOffset < fieldAlign)
946 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
947 }
948
949 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000950 }
Chris Lattner68061312009-01-24 21:53:27 +0000951 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000952
Ken Dyckcc56c542011-01-15 18:38:59 +0000953 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000954}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000955
John McCall87fe5d52010-05-20 01:18:31 +0000956std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000957ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000958 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000959 return std::make_pair(toCharUnitsFromBits(Info.first),
960 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000961}
962
963std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000964ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000965 return getTypeInfoInChars(T.getTypePtr());
966}
967
Daniel Dunbarc6475872012-03-09 04:12:54 +0000968std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
969 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
970 if (it != MemoizedTypeInfo.end())
971 return it->second;
972
973 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
974 MemoizedTypeInfo.insert(std::make_pair(T, Info));
975 return Info;
976}
977
978/// getTypeInfoImpl - Return the size of the specified type, in bits. This
979/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000980///
981/// FIXME: Pointers into different addr spaces could have different sizes and
982/// alignment requirements: getPointerInfo should take an AddrSpace, this
983/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000984std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000985ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000986 uint64_t Width=0;
987 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000988 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000989#define TYPE(Class, Base)
990#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000991#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000992#define DEPENDENT_TYPE(Class, Base) case Type::Class:
993#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000994 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000995
Chris Lattner355332d2007-07-13 22:27:08 +0000996 case Type::FunctionNoProto:
997 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000998 // GCC extension: alignof(function) = 32 bits
999 Width = 0;
1000 Align = 32;
1001 break;
1002
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001003 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001004 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001005 Width = 0;
1006 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1007 break;
1008
Steve Naroff5c131802007-08-30 01:06:46 +00001009 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001010 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner37e05872008-03-05 18:54:05 +00001012 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001013 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001014 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1015 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001016 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001017 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001018 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001019 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001020 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001021 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001022 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001023 const VectorType *VT = cast<VectorType>(T);
1024 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1025 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001026 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001027 // If the alignment is not a power of 2, round up to the next power of 2.
1028 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001029 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001030 Align = llvm::NextPowerOf2(Align);
1031 Width = llvm::RoundUpToAlignment(Width, Align);
1032 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001033 break;
1034 }
Chris Lattner647fb222007-07-18 18:26:58 +00001035
Chris Lattner7570e9c2008-03-08 08:52:55 +00001036 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001037 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001038 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001039 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001040 // GCC extension: alignof(void) = 8 bits.
1041 Width = 0;
1042 Align = 8;
1043 break;
1044
Chris Lattner6a4f7452007-12-19 19:23:28 +00001045 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001046 Width = Target->getBoolWidth();
1047 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001048 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001049 case BuiltinType::Char_S:
1050 case BuiltinType::Char_U:
1051 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001052 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001053 Width = Target->getCharWidth();
1054 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001055 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001056 case BuiltinType::WChar_S:
1057 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001058 Width = Target->getWCharWidth();
1059 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001060 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001061 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001062 Width = Target->getChar16Width();
1063 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001064 break;
1065 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001066 Width = Target->getChar32Width();
1067 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001068 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001069 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001070 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001071 Width = Target->getShortWidth();
1072 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001073 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001074 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001075 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001076 Width = Target->getIntWidth();
1077 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001078 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001079 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001080 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001081 Width = Target->getLongWidth();
1082 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001083 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001084 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001085 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001086 Width = Target->getLongLongWidth();
1087 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001088 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001089 case BuiltinType::Int128:
1090 case BuiltinType::UInt128:
1091 Width = 128;
1092 Align = 128; // int128_t is 128-bit aligned on all targets.
1093 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001094 case BuiltinType::Half:
1095 Width = Target->getHalfWidth();
1096 Align = Target->getHalfAlign();
1097 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001098 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001099 Width = Target->getFloatWidth();
1100 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001101 break;
1102 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001103 Width = Target->getDoubleWidth();
1104 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001105 break;
1106 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001107 Width = Target->getLongDoubleWidth();
1108 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001109 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001110 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001111 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1112 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001113 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001114 case BuiltinType::ObjCId:
1115 case BuiltinType::ObjCClass:
1116 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001117 Width = Target->getPointerWidth(0);
1118 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001119 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001120 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001121 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001122 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001123 Width = Target->getPointerWidth(0);
1124 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001125 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001126 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001127 unsigned AS = getTargetAddressSpace(
1128 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001129 Width = Target->getPointerWidth(AS);
1130 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001131 break;
1132 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001133 case Type::LValueReference:
1134 case Type::RValueReference: {
1135 // alignof and sizeof should never enter this code path here, so we go
1136 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001137 unsigned AS = getTargetAddressSpace(
1138 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001139 Width = Target->getPointerWidth(AS);
1140 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001141 break;
1142 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001143 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001144 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001145 Width = Target->getPointerWidth(AS);
1146 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001147 break;
1148 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001149 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001150 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001151 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001152 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001153 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001154 Align = PtrDiffInfo.second;
1155 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001156 }
Chris Lattner647fb222007-07-18 18:26:58 +00001157 case Type::Complex: {
1158 // Complex types have the same alignment as their elements, but twice the
1159 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001160 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001161 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001162 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001163 Align = EltInfo.second;
1164 break;
1165 }
John McCall8b07ec22010-05-15 11:32:37 +00001166 case Type::ObjCObject:
1167 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001168 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001169 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001170 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001171 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001172 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001173 break;
1174 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001175 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001176 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001177 const TagType *TT = cast<TagType>(T);
1178
1179 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001180 Width = 8;
1181 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001182 break;
1183 }
Mike Stump11289f42009-09-09 15:08:12 +00001184
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001185 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001186 return getTypeInfo(ET->getDecl()->getIntegerType());
1187
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001188 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001189 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001190 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001191 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001192 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001193 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001194
Chris Lattner63d2b362009-10-22 05:17:15 +00001195 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001196 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1197 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001198
Richard Smith30482bc2011-02-20 03:19:35 +00001199 case Type::Auto: {
1200 const AutoType *A = cast<AutoType>(T);
1201 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001202 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001203 }
1204
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001205 case Type::Paren:
1206 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1207
Douglas Gregoref462e62009-04-30 17:32:17 +00001208 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001209 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001210 std::pair<uint64_t, unsigned> Info
1211 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001212 // If the typedef has an aligned attribute on it, it overrides any computed
1213 // alignment we have. This violates the GCC documentation (which says that
1214 // attribute(aligned) can only round up) but matches its implementation.
1215 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1216 Align = AttrAlign;
1217 else
1218 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001219 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001220 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001221 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001222
1223 case Type::TypeOfExpr:
1224 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1225 .getTypePtr());
1226
1227 case Type::TypeOf:
1228 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1229
Anders Carlsson81df7b82009-06-24 19:06:50 +00001230 case Type::Decltype:
1231 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1232 .getTypePtr());
1233
Alexis Hunte852b102011-05-24 22:41:36 +00001234 case Type::UnaryTransform:
1235 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1236
Abramo Bagnara6150c882010-05-11 21:36:43 +00001237 case Type::Elaborated:
1238 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001239
John McCall81904512011-01-06 01:58:22 +00001240 case Type::Attributed:
1241 return getTypeInfo(
1242 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1243
Richard Smith3f1b5d02011-05-05 21:57:07 +00001244 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001245 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001246 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001247 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1248 // A type alias template specialization may refer to a typedef with the
1249 // aligned attribute on it.
1250 if (TST->isTypeAlias())
1251 return getTypeInfo(TST->getAliasedType().getTypePtr());
1252 else
1253 return getTypeInfo(getCanonicalType(T));
1254 }
1255
Eli Friedman0dfb8892011-10-06 23:00:33 +00001256 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001257 std::pair<uint64_t, unsigned> Info
1258 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1259 Width = Info.first;
1260 Align = Info.second;
1261 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1262 llvm::isPowerOf2_64(Width)) {
1263 // We can potentially perform lock-free atomic operations for this
1264 // type; promote the alignment appropriately.
1265 // FIXME: We could potentially promote the width here as well...
1266 // is that worthwhile? (Non-struct atomic types generally have
1267 // power-of-two size anyway, but structs might not. Requires a bit
1268 // of implementation work to make sure we zero out the extra bits.)
1269 Align = static_cast<unsigned>(Width);
1270 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001271 }
1272
Douglas Gregoref462e62009-04-30 17:32:17 +00001273 }
Mike Stump11289f42009-09-09 15:08:12 +00001274
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001275 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001276 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001277}
1278
Ken Dyckcc56c542011-01-15 18:38:59 +00001279/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1280CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1281 return CharUnits::fromQuantity(BitSize / getCharWidth());
1282}
1283
Ken Dyckb0fcc592011-02-11 01:54:29 +00001284/// toBits - Convert a size in characters to a size in characters.
1285int64_t ASTContext::toBits(CharUnits CharSize) const {
1286 return CharSize.getQuantity() * getCharWidth();
1287}
1288
Ken Dyck8c89d592009-12-22 14:23:30 +00001289/// getTypeSizeInChars - Return the size of the specified type, in characters.
1290/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001291CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001292 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001293}
Jay Foad39c79802011-01-12 09:06:06 +00001294CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001295 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001296}
1297
Ken Dycka6046ab2010-01-26 17:25:18 +00001298/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001299/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001300CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001301 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001302}
Jay Foad39c79802011-01-12 09:06:06 +00001303CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001304 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001305}
1306
Chris Lattnera3402cd2009-01-27 18:08:34 +00001307/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1308/// type for the current target in bits. This can be different than the ABI
1309/// alignment in cases where it is beneficial for performance to overalign
1310/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001311unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001312 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001313
1314 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001315 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001316 T = CT->getElementType().getTypePtr();
1317 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001318 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1319 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001320 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1321
Chris Lattnera3402cd2009-01-27 18:08:34 +00001322 return ABIAlign;
1323}
1324
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001325/// DeepCollectObjCIvars -
1326/// This routine first collects all declared, but not synthesized, ivars in
1327/// super class and then collects all ivars, including those synthesized for
1328/// current class. This routine is used for implementation of current class
1329/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001330///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001331void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1332 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001333 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001334 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1335 DeepCollectObjCIvars(SuperClass, false, Ivars);
1336 if (!leafClass) {
1337 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1338 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001339 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001340 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001341 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001342 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001343 Iv= Iv->getNextIvar())
1344 Ivars.push_back(Iv);
1345 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001346}
1347
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001348/// CollectInheritedProtocols - Collect all protocols in current class and
1349/// those inherited by it.
1350void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001351 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001352 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001353 // We can use protocol_iterator here instead of
1354 // all_referenced_protocol_iterator since we are walking all categories.
1355 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1356 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001357 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001358 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001359 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001360 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001361 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001362 CollectInheritedProtocols(*P, Protocols);
1363 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001364 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001365
1366 // Categories of this Interface.
1367 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1368 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1369 CollectInheritedProtocols(CDeclChain, Protocols);
1370 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1371 while (SD) {
1372 CollectInheritedProtocols(SD, Protocols);
1373 SD = SD->getSuperClass();
1374 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001375 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001376 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001377 PE = OC->protocol_end(); P != PE; ++P) {
1378 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(),
1381 PE = Proto->protocol_end(); P != PE; ++P)
1382 CollectInheritedProtocols(*P, Protocols);
1383 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001384 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001385 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1386 PE = OP->protocol_end(); P != PE; ++P) {
1387 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001388 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001389 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1390 PE = Proto->protocol_end(); P != PE; ++P)
1391 CollectInheritedProtocols(*P, Protocols);
1392 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001393 }
1394}
1395
Jay Foad39c79802011-01-12 09:06:06 +00001396unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001397 unsigned count = 0;
1398 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001399 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1400 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001401 count += CDecl->ivar_size();
1402
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001403 // Count ivar defined in this class's implementation. This
1404 // includes synthesized ivars.
1405 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001406 count += ImplDecl->ivar_size();
1407
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001408 return count;
1409}
1410
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001411bool ASTContext::isSentinelNullExpr(const Expr *E) {
1412 if (!E)
1413 return false;
1414
1415 // nullptr_t is always treated as null.
1416 if (E->getType()->isNullPtrType()) return true;
1417
1418 if (E->getType()->isAnyPointerType() &&
1419 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1420 Expr::NPC_ValueDependentIsNull))
1421 return true;
1422
1423 // Unfortunately, __null has type 'int'.
1424 if (isa<GNUNullExpr>(E)) return true;
1425
1426 return false;
1427}
1428
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001429/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1430ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1431 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1432 I = ObjCImpls.find(D);
1433 if (I != ObjCImpls.end())
1434 return cast<ObjCImplementationDecl>(I->second);
1435 return 0;
1436}
1437/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1438ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1439 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1440 I = ObjCImpls.find(D);
1441 if (I != ObjCImpls.end())
1442 return cast<ObjCCategoryImplDecl>(I->second);
1443 return 0;
1444}
1445
1446/// \brief Set the implementation of ObjCInterfaceDecl.
1447void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1448 ObjCImplementationDecl *ImplD) {
1449 assert(IFaceD && ImplD && "Passed null params");
1450 ObjCImpls[IFaceD] = ImplD;
1451}
1452/// \brief Set the implementation of ObjCCategoryDecl.
1453void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1454 ObjCCategoryImplDecl *ImplD) {
1455 assert(CatD && ImplD && "Passed null params");
1456 ObjCImpls[CatD] = ImplD;
1457}
1458
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001459ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1460 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1461 return ID;
1462 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1463 return CD->getClassInterface();
1464 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1465 return IMD->getClassInterface();
1466
1467 return 0;
1468}
1469
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001470/// \brief Get the copy initialization expression of VarDecl,or NULL if
1471/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001472Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001473 assert(VD && "Passed null params");
1474 assert(VD->hasAttr<BlocksAttr>() &&
1475 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001476 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001477 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001478 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1479}
1480
1481/// \brief Set the copy inialization expression of a block var decl.
1482void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1483 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001484 assert(VD->hasAttr<BlocksAttr>() &&
1485 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001486 BlockVarCopyInits[VD] = Init;
1487}
1488
John McCallbcd03502009-12-07 02:54:59 +00001489TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001490 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001491 if (!DataSize)
1492 DataSize = TypeLoc::getFullDataSizeForType(T);
1493 else
1494 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001495 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001496
John McCallbcd03502009-12-07 02:54:59 +00001497 TypeSourceInfo *TInfo =
1498 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1499 new (TInfo) TypeSourceInfo(T);
1500 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001501}
1502
John McCallbcd03502009-12-07 02:54:59 +00001503TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001504 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001505 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001506 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001507 return DI;
1508}
1509
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001510const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001511ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001512 return getObjCLayout(D, 0);
1513}
1514
1515const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001516ASTContext::getASTObjCImplementationLayout(
1517 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001518 return getObjCLayout(D->getClassInterface(), D);
1519}
1520
Chris Lattner983a8bb2007-07-13 22:13:22 +00001521//===----------------------------------------------------------------------===//
1522// Type creation/memoization methods
1523//===----------------------------------------------------------------------===//
1524
Jay Foad39c79802011-01-12 09:06:06 +00001525QualType
John McCall33ddac02011-01-19 10:06:00 +00001526ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1527 unsigned fastQuals = quals.getFastQualifiers();
1528 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001529
1530 // Check if we've already instantiated this type.
1531 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001532 ExtQuals::Profile(ID, baseType, quals);
1533 void *insertPos = 0;
1534 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1535 assert(eq->getQualifiers() == quals);
1536 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001537 }
1538
John McCall33ddac02011-01-19 10:06:00 +00001539 // If the base type is not canonical, make the appropriate canonical type.
1540 QualType canon;
1541 if (!baseType->isCanonicalUnqualified()) {
1542 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001543 canonSplit.Quals.addConsistentQualifiers(quals);
1544 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001545
1546 // Re-find the insert position.
1547 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1548 }
1549
1550 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1551 ExtQualNodes.InsertNode(eq, insertPos);
1552 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001553}
1554
Jay Foad39c79802011-01-12 09:06:06 +00001555QualType
1556ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001557 QualType CanT = getCanonicalType(T);
1558 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001559 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001560
John McCall8ccfcb52009-09-24 19:53:00 +00001561 // If we are composing extended qualifiers together, merge together
1562 // into one ExtQuals node.
1563 QualifierCollector Quals;
1564 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001565
John McCall8ccfcb52009-09-24 19:53:00 +00001566 // If this type already has an address space specified, it cannot get
1567 // another one.
1568 assert(!Quals.hasAddressSpace() &&
1569 "Type cannot be in multiple addr spaces!");
1570 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001571
John McCall8ccfcb52009-09-24 19:53:00 +00001572 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001573}
1574
Chris Lattnerd60183d2009-02-18 22:53:11 +00001575QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001576 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001577 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001578 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001579 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001580
John McCall53fa7142010-12-24 02:08:15 +00001581 if (const PointerType *ptr = T->getAs<PointerType>()) {
1582 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001583 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001584 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1585 return getPointerType(ResultType);
1586 }
1587 }
Mike Stump11289f42009-09-09 15:08:12 +00001588
John McCall8ccfcb52009-09-24 19:53:00 +00001589 // If we are composing extended qualifiers together, merge together
1590 // into one ExtQuals node.
1591 QualifierCollector Quals;
1592 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001593
John McCall8ccfcb52009-09-24 19:53:00 +00001594 // If this type already has an ObjCGC specified, it cannot get
1595 // another one.
1596 assert(!Quals.hasObjCGCAttr() &&
1597 "Type cannot have multiple ObjCGCs!");
1598 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001599
John McCall8ccfcb52009-09-24 19:53:00 +00001600 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001601}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001602
John McCall4f5019e2010-12-19 02:44:49 +00001603const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1604 FunctionType::ExtInfo Info) {
1605 if (T->getExtInfo() == Info)
1606 return T;
1607
1608 QualType Result;
1609 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1610 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1611 } else {
1612 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1613 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1614 EPI.ExtInfo = Info;
1615 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1616 FPT->getNumArgs(), EPI);
1617 }
1618
1619 return cast<FunctionType>(Result.getTypePtr());
1620}
1621
Chris Lattnerc6395932007-06-22 20:56:16 +00001622/// getComplexType - Return the uniqued reference to the type for a complex
1623/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001624QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001625 // Unique pointers, to guarantee there is only one pointer of a particular
1626 // structure.
1627 llvm::FoldingSetNodeID ID;
1628 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001629
Chris Lattnerc6395932007-06-22 20:56:16 +00001630 void *InsertPos = 0;
1631 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1632 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001633
Chris Lattnerc6395932007-06-22 20:56:16 +00001634 // If the pointee type isn't canonical, this won't be a canonical type either,
1635 // so fill in the canonical type field.
1636 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001637 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001638 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001639
Chris Lattnerc6395932007-06-22 20:56:16 +00001640 // Get the new insert position for the node we care about.
1641 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001642 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001643 }
John McCall90d1c2d2009-09-24 23:30:46 +00001644 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001645 Types.push_back(New);
1646 ComplexTypes.InsertNode(New, InsertPos);
1647 return QualType(New, 0);
1648}
1649
Chris Lattner970e54e2006-11-12 00:37:36 +00001650/// getPointerType - Return the uniqued reference to the type for a pointer to
1651/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001652QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001653 // Unique pointers, to guarantee there is only one pointer of a particular
1654 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001655 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001656 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Chris Lattner67521df2007-01-27 01:29:36 +00001658 void *InsertPos = 0;
1659 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001660 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001661
Chris Lattner7ccecb92006-11-12 08:50:50 +00001662 // If the pointee type isn't canonical, this won't be a canonical type either,
1663 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001664 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001665 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001666 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001667
Chris Lattner67521df2007-01-27 01:29:36 +00001668 // Get the new insert position for the node we care about.
1669 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001670 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001671 }
John McCall90d1c2d2009-09-24 23:30:46 +00001672 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001673 Types.push_back(New);
1674 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001675 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001676}
1677
Mike Stump11289f42009-09-09 15:08:12 +00001678/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001679/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001680QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001681 assert(T->isFunctionType() && "block of function types only");
1682 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001683 // structure.
1684 llvm::FoldingSetNodeID ID;
1685 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001686
Steve Naroffec33ed92008-08-27 16:04:49 +00001687 void *InsertPos = 0;
1688 if (BlockPointerType *PT =
1689 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1690 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001691
1692 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001693 // type either so fill in the canonical type field.
1694 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001695 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001696 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001697
Steve Naroffec33ed92008-08-27 16:04:49 +00001698 // Get the new insert position for the node we care about.
1699 BlockPointerType *NewIP =
1700 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001701 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001702 }
John McCall90d1c2d2009-09-24 23:30:46 +00001703 BlockPointerType *New
1704 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001705 Types.push_back(New);
1706 BlockPointerTypes.InsertNode(New, InsertPos);
1707 return QualType(New, 0);
1708}
1709
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001710/// getLValueReferenceType - Return the uniqued reference to the type for an
1711/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001712QualType
1713ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001714 assert(getCanonicalType(T) != OverloadTy &&
1715 "Unresolved overloaded function type");
1716
Bill Wendling3708c182007-05-27 10:15:43 +00001717 // Unique pointers, to guarantee there is only one pointer of a particular
1718 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001719 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001720 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001721
1722 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001723 if (LValueReferenceType *RT =
1724 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001725 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001726
John McCallfc93cf92009-10-22 22:37:11 +00001727 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1728
Bill Wendling3708c182007-05-27 10:15:43 +00001729 // If the referencee type isn't canonical, this won't be a canonical type
1730 // either, so fill in the canonical type field.
1731 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001732 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1733 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1734 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001735
Bill Wendling3708c182007-05-27 10:15:43 +00001736 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001737 LValueReferenceType *NewIP =
1738 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001739 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001740 }
1741
John McCall90d1c2d2009-09-24 23:30:46 +00001742 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001743 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1744 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001745 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001746 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001747
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001748 return QualType(New, 0);
1749}
1750
1751/// getRValueReferenceType - Return the uniqued reference to the type for an
1752/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001753QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001754 // Unique pointers, to guarantee there is only one pointer of a particular
1755 // structure.
1756 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001757 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001758
1759 void *InsertPos = 0;
1760 if (RValueReferenceType *RT =
1761 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1762 return QualType(RT, 0);
1763
John McCallfc93cf92009-10-22 22:37:11 +00001764 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1765
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001766 // If the referencee type isn't canonical, this won't be a canonical type
1767 // either, so fill in the canonical type field.
1768 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001769 if (InnerRef || !T.isCanonical()) {
1770 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1771 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001772
1773 // Get the new insert position for the node we care about.
1774 RValueReferenceType *NewIP =
1775 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001776 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001777 }
1778
John McCall90d1c2d2009-09-24 23:30:46 +00001779 RValueReferenceType *New
1780 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001781 Types.push_back(New);
1782 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001783 return QualType(New, 0);
1784}
1785
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001786/// getMemberPointerType - Return the uniqued reference to the type for a
1787/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001788QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001789 // Unique pointers, to guarantee there is only one pointer of a particular
1790 // structure.
1791 llvm::FoldingSetNodeID ID;
1792 MemberPointerType::Profile(ID, T, Cls);
1793
1794 void *InsertPos = 0;
1795 if (MemberPointerType *PT =
1796 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1797 return QualType(PT, 0);
1798
1799 // If the pointee or class type isn't canonical, this won't be a canonical
1800 // type either, so fill in the canonical type field.
1801 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001802 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001803 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1804
1805 // Get the new insert position for the node we care about.
1806 MemberPointerType *NewIP =
1807 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001808 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001809 }
John McCall90d1c2d2009-09-24 23:30:46 +00001810 MemberPointerType *New
1811 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001812 Types.push_back(New);
1813 MemberPointerTypes.InsertNode(New, InsertPos);
1814 return QualType(New, 0);
1815}
1816
Mike Stump11289f42009-09-09 15:08:12 +00001817/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001818/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001819QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001820 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001821 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001822 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001823 assert((EltTy->isDependentType() ||
1824 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001825 "Constant array of VLAs is illegal!");
1826
Chris Lattnere2df3f92009-05-13 04:12:56 +00001827 // Convert the array size into a canonical width matching the pointer size for
1828 // the target.
1829 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001830 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001831 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001832
Chris Lattner23b7eb62007-06-15 23:05:46 +00001833 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001834 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001835
Chris Lattner36f8e652007-01-27 08:31:04 +00001836 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001837 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001838 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001839 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001840
John McCall33ddac02011-01-19 10:06:00 +00001841 // If the element type isn't canonical or has qualifiers, this won't
1842 // be a canonical type either, so fill in the canonical type field.
1843 QualType Canon;
1844 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1845 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001846 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001847 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001848 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001849
Chris Lattner36f8e652007-01-27 08:31:04 +00001850 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001851 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001852 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001853 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
John McCall90d1c2d2009-09-24 23:30:46 +00001856 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001857 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001858 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001859 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001860 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001861}
1862
John McCall06549462011-01-18 08:40:38 +00001863/// getVariableArrayDecayedType - Turns the given type, which may be
1864/// variably-modified, into the corresponding type with all the known
1865/// sizes replaced with [*].
1866QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1867 // Vastly most common case.
1868 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001869
John McCall06549462011-01-18 08:40:38 +00001870 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001871
John McCall06549462011-01-18 08:40:38 +00001872 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001873 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001874 switch (ty->getTypeClass()) {
1875#define TYPE(Class, Base)
1876#define ABSTRACT_TYPE(Class, Base)
1877#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1878#include "clang/AST/TypeNodes.def"
1879 llvm_unreachable("didn't desugar past all non-canonical types?");
1880
1881 // These types should never be variably-modified.
1882 case Type::Builtin:
1883 case Type::Complex:
1884 case Type::Vector:
1885 case Type::ExtVector:
1886 case Type::DependentSizedExtVector:
1887 case Type::ObjCObject:
1888 case Type::ObjCInterface:
1889 case Type::ObjCObjectPointer:
1890 case Type::Record:
1891 case Type::Enum:
1892 case Type::UnresolvedUsing:
1893 case Type::TypeOfExpr:
1894 case Type::TypeOf:
1895 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001896 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001897 case Type::DependentName:
1898 case Type::InjectedClassName:
1899 case Type::TemplateSpecialization:
1900 case Type::DependentTemplateSpecialization:
1901 case Type::TemplateTypeParm:
1902 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001903 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001904 case Type::PackExpansion:
1905 llvm_unreachable("type should never be variably-modified");
1906
1907 // These types can be variably-modified but should never need to
1908 // further decay.
1909 case Type::FunctionNoProto:
1910 case Type::FunctionProto:
1911 case Type::BlockPointer:
1912 case Type::MemberPointer:
1913 return type;
1914
1915 // These types can be variably-modified. All these modifications
1916 // preserve structure except as noted by comments.
1917 // TODO: if we ever care about optimizing VLAs, there are no-op
1918 // optimizations available here.
1919 case Type::Pointer:
1920 result = getPointerType(getVariableArrayDecayedType(
1921 cast<PointerType>(ty)->getPointeeType()));
1922 break;
1923
1924 case Type::LValueReference: {
1925 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1926 result = getLValueReferenceType(
1927 getVariableArrayDecayedType(lv->getPointeeType()),
1928 lv->isSpelledAsLValue());
1929 break;
1930 }
1931
1932 case Type::RValueReference: {
1933 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1934 result = getRValueReferenceType(
1935 getVariableArrayDecayedType(lv->getPointeeType()));
1936 break;
1937 }
1938
Eli Friedman0dfb8892011-10-06 23:00:33 +00001939 case Type::Atomic: {
1940 const AtomicType *at = cast<AtomicType>(ty);
1941 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1942 break;
1943 }
1944
John McCall06549462011-01-18 08:40:38 +00001945 case Type::ConstantArray: {
1946 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1947 result = getConstantArrayType(
1948 getVariableArrayDecayedType(cat->getElementType()),
1949 cat->getSize(),
1950 cat->getSizeModifier(),
1951 cat->getIndexTypeCVRQualifiers());
1952 break;
1953 }
1954
1955 case Type::DependentSizedArray: {
1956 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1957 result = getDependentSizedArrayType(
1958 getVariableArrayDecayedType(dat->getElementType()),
1959 dat->getSizeExpr(),
1960 dat->getSizeModifier(),
1961 dat->getIndexTypeCVRQualifiers(),
1962 dat->getBracketsRange());
1963 break;
1964 }
1965
1966 // Turn incomplete types into [*] types.
1967 case Type::IncompleteArray: {
1968 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1969 result = getVariableArrayType(
1970 getVariableArrayDecayedType(iat->getElementType()),
1971 /*size*/ 0,
1972 ArrayType::Normal,
1973 iat->getIndexTypeCVRQualifiers(),
1974 SourceRange());
1975 break;
1976 }
1977
1978 // Turn VLA types into [*] types.
1979 case Type::VariableArray: {
1980 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1981 result = getVariableArrayType(
1982 getVariableArrayDecayedType(vat->getElementType()),
1983 /*size*/ 0,
1984 ArrayType::Star,
1985 vat->getIndexTypeCVRQualifiers(),
1986 vat->getBracketsRange());
1987 break;
1988 }
1989 }
1990
1991 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001992 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001993}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001994
Steve Naroffcadebd02007-08-30 18:14:25 +00001995/// getVariableArrayType - Returns a non-unique reference to the type for a
1996/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001997QualType ASTContext::getVariableArrayType(QualType EltTy,
1998 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001999 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002000 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002001 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002002 // Since we don't unique expressions, it isn't possible to unique VLA's
2003 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002004 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002005
John McCall33ddac02011-01-19 10:06:00 +00002006 // Be sure to pull qualifiers off the element type.
2007 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2008 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002009 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002010 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002011 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002012 }
2013
John McCall90d1c2d2009-09-24 23:30:46 +00002014 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002015 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002016
2017 VariableArrayTypes.push_back(New);
2018 Types.push_back(New);
2019 return QualType(New, 0);
2020}
2021
Douglas Gregor4619e432008-12-05 23:32:09 +00002022/// getDependentSizedArrayType - Returns a non-unique reference to
2023/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002024/// type.
John McCall33ddac02011-01-19 10:06:00 +00002025QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2026 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002027 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002028 unsigned elementTypeQuals,
2029 SourceRange brackets) const {
2030 assert((!numElements || numElements->isTypeDependent() ||
2031 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002032 "Size must be type- or value-dependent!");
2033
John McCall33ddac02011-01-19 10:06:00 +00002034 // Dependently-sized array types that do not have a specified number
2035 // of elements will have their sizes deduced from a dependent
2036 // initializer. We do no canonicalization here at all, which is okay
2037 // because they can't be used in most locations.
2038 if (!numElements) {
2039 DependentSizedArrayType *newType
2040 = new (*this, TypeAlignment)
2041 DependentSizedArrayType(*this, elementType, QualType(),
2042 numElements, ASM, elementTypeQuals,
2043 brackets);
2044 Types.push_back(newType);
2045 return QualType(newType, 0);
2046 }
2047
2048 // Otherwise, we actually build a new type every time, but we
2049 // also build a canonical type.
2050
2051 SplitQualType canonElementType = getCanonicalType(elementType).split();
2052
2053 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002054 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002055 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002056 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002057 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002058
John McCall33ddac02011-01-19 10:06:00 +00002059 // Look for an existing type with these properties.
2060 DependentSizedArrayType *canonTy =
2061 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002062
John McCall33ddac02011-01-19 10:06:00 +00002063 // If we don't have one, build one.
2064 if (!canonTy) {
2065 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002066 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002067 QualType(), numElements, ASM, elementTypeQuals,
2068 brackets);
2069 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2070 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002071 }
2072
John McCall33ddac02011-01-19 10:06:00 +00002073 // Apply qualifiers from the element type to the array.
2074 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002075 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002076
John McCall33ddac02011-01-19 10:06:00 +00002077 // If we didn't need extra canonicalization for the element type,
2078 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002079 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002080 return canon;
2081
2082 // Otherwise, we need to build a type which follows the spelling
2083 // of the element type.
2084 DependentSizedArrayType *sugaredType
2085 = new (*this, TypeAlignment)
2086 DependentSizedArrayType(*this, elementType, canon, numElements,
2087 ASM, elementTypeQuals, brackets);
2088 Types.push_back(sugaredType);
2089 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002090}
2091
John McCall33ddac02011-01-19 10:06:00 +00002092QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002093 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002094 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002095 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002096 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002097
John McCall33ddac02011-01-19 10:06:00 +00002098 void *insertPos = 0;
2099 if (IncompleteArrayType *iat =
2100 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2101 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002102
2103 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002104 // either, so fill in the canonical type field. We also have to pull
2105 // qualifiers off the element type.
2106 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002107
John McCall33ddac02011-01-19 10:06:00 +00002108 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2109 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002110 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002111 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002112 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002113
2114 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002115 IncompleteArrayType *existing =
2116 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2117 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002118 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002119
John McCall33ddac02011-01-19 10:06:00 +00002120 IncompleteArrayType *newType = new (*this, TypeAlignment)
2121 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002122
John McCall33ddac02011-01-19 10:06:00 +00002123 IncompleteArrayTypes.InsertNode(newType, insertPos);
2124 Types.push_back(newType);
2125 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002126}
2127
Steve Naroff91fcddb2007-07-18 18:00:27 +00002128/// getVectorType - Return the unique reference to a vector type of
2129/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002130QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002131 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002132 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002133
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002134 // Check if we've already instantiated a vector of this type.
2135 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002136 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002137
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002138 void *InsertPos = 0;
2139 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2140 return QualType(VTP, 0);
2141
2142 // If the element type isn't canonical, this won't be a canonical type either,
2143 // so fill in the canonical type field.
2144 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002145 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002146 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002147
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002148 // Get the new insert position for the node we care about.
2149 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002150 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002151 }
John McCall90d1c2d2009-09-24 23:30:46 +00002152 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002153 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002154 VectorTypes.InsertNode(New, InsertPos);
2155 Types.push_back(New);
2156 return QualType(New, 0);
2157}
2158
Nate Begemance4d7fc2008-04-18 23:10:10 +00002159/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002160/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002161QualType
2162ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002163 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002164
Steve Naroff91fcddb2007-07-18 18:00:27 +00002165 // Check if we've already instantiated a vector of this type.
2166 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002167 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002168 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002169 void *InsertPos = 0;
2170 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2171 return QualType(VTP, 0);
2172
2173 // If the element type isn't canonical, this won't be a canonical type either,
2174 // so fill in the canonical type field.
2175 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002176 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002177 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002178
Steve Naroff91fcddb2007-07-18 18:00:27 +00002179 // Get the new insert position for the node we care about.
2180 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002181 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002182 }
John McCall90d1c2d2009-09-24 23:30:46 +00002183 ExtVectorType *New = new (*this, TypeAlignment)
2184 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002185 VectorTypes.InsertNode(New, InsertPos);
2186 Types.push_back(New);
2187 return QualType(New, 0);
2188}
2189
Jay Foad39c79802011-01-12 09:06:06 +00002190QualType
2191ASTContext::getDependentSizedExtVectorType(QualType vecType,
2192 Expr *SizeExpr,
2193 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002194 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002195 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002196 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002197
Douglas Gregor352169a2009-07-31 03:54:25 +00002198 void *InsertPos = 0;
2199 DependentSizedExtVectorType *Canon
2200 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2201 DependentSizedExtVectorType *New;
2202 if (Canon) {
2203 // We already have a canonical version of this array type; use it as
2204 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002205 New = new (*this, TypeAlignment)
2206 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2207 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002208 } else {
2209 QualType CanonVecTy = getCanonicalType(vecType);
2210 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002211 New = new (*this, TypeAlignment)
2212 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2213 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002214
2215 DependentSizedExtVectorType *CanonCheck
2216 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2217 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2218 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002219 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2220 } else {
2221 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2222 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002223 New = new (*this, TypeAlignment)
2224 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002225 }
2226 }
Mike Stump11289f42009-09-09 15:08:12 +00002227
Douglas Gregor758a8692009-06-17 21:51:59 +00002228 Types.push_back(New);
2229 return QualType(New, 0);
2230}
2231
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002232/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002233///
Jay Foad39c79802011-01-12 09:06:06 +00002234QualType
2235ASTContext::getFunctionNoProtoType(QualType ResultTy,
2236 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002237 const CallingConv DefaultCC = Info.getCC();
2238 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2239 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002240 // Unique functions, to guarantee there is only one function of a particular
2241 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002242 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002243 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002244
Chris Lattner47955de2007-01-27 08:37:20 +00002245 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002246 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002247 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002248 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002249
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002250 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002251 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002252 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002253 Canonical =
2254 getFunctionNoProtoType(getCanonicalType(ResultTy),
2255 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002256
Chris Lattner47955de2007-01-27 08:37:20 +00002257 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002258 FunctionNoProtoType *NewIP =
2259 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002260 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002261 }
Mike Stump11289f42009-09-09 15:08:12 +00002262
Roman Divacky65b88cd2011-03-01 17:40:53 +00002263 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002264 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002265 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002266 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002267 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002268 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002269}
2270
2271/// getFunctionType - Return a normal function type with a typed argument
2272/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002273QualType
2274ASTContext::getFunctionType(QualType ResultTy,
2275 const QualType *ArgArray, unsigned NumArgs,
2276 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002277 // Unique functions, to guarantee there is only one function of a particular
2278 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002279 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002280 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002281
2282 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002283 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002284 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002285 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002286
2287 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002288 bool isCanonical =
2289 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2290 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002291 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002292 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002293 isCanonical = false;
2294
Roman Divacky65b88cd2011-03-01 17:40:53 +00002295 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2296 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2297 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002298
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002299 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002300 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002301 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002302 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002303 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002304 CanonicalArgs.reserve(NumArgs);
2305 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002306 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002307
John McCalldb40c7f2010-12-14 08:05:40 +00002308 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002309 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002310 CanonicalEPI.ExceptionSpecType = EST_None;
2311 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002312 CanonicalEPI.ExtInfo
2313 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2314
Chris Lattner76a00cf2008-04-06 22:59:24 +00002315 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002316 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002317 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002318
Chris Lattnerfd4de792007-01-27 01:15:32 +00002319 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002320 FunctionProtoType *NewIP =
2321 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002322 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002323 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002324
John McCall31168b02011-06-15 23:02:42 +00002325 // FunctionProtoType objects are allocated with extra bytes after
2326 // them for three variable size arrays at the end:
2327 // - parameter types
2328 // - exception types
2329 // - consumed-arguments flags
2330 // Instead of the exception types, there could be a noexcept
2331 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002332 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002333 NumArgs * sizeof(QualType);
2334 if (EPI.ExceptionSpecType == EST_Dynamic)
2335 Size += EPI.NumExceptions * sizeof(QualType);
2336 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002337 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002338 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002339 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002340 }
John McCall31168b02011-06-15 23:02:42 +00002341 if (EPI.ConsumedArguments)
2342 Size += NumArgs * sizeof(bool);
2343
John McCalldb40c7f2010-12-14 08:05:40 +00002344 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002345 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2346 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002347 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002348 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002349 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002350 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002351}
Chris Lattneref51c202006-11-10 07:17:23 +00002352
John McCalle78aac42010-03-10 03:28:59 +00002353#ifndef NDEBUG
2354static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2355 if (!isa<CXXRecordDecl>(D)) return false;
2356 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2357 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2358 return true;
2359 if (RD->getDescribedClassTemplate() &&
2360 !isa<ClassTemplateSpecializationDecl>(RD))
2361 return true;
2362 return false;
2363}
2364#endif
2365
2366/// getInjectedClassNameType - Return the unique reference to the
2367/// injected class name type for the specified templated declaration.
2368QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002369 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002370 assert(NeedsInjectedClassNameType(Decl));
2371 if (Decl->TypeForDecl) {
2372 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002373 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002374 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2375 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2376 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2377 } else {
John McCall424cec92011-01-19 06:33:43 +00002378 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002379 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002380 Decl->TypeForDecl = newType;
2381 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002382 }
2383 return QualType(Decl->TypeForDecl, 0);
2384}
2385
Douglas Gregor83a586e2008-04-13 21:07:44 +00002386/// getTypeDeclType - Return the unique reference to the type for the
2387/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002388QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002389 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002390 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002391
Richard Smithdda56e42011-04-15 14:24:37 +00002392 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002393 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002394
John McCall96f0b5f2010-03-10 06:48:02 +00002395 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2396 "Template type parameter types are always available.");
2397
John McCall81e38502010-02-16 03:57:14 +00002398 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002399 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002400 "struct/union has previous declaration");
2401 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002402 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002403 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002404 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002405 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002406 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002407 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002408 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002409 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2410 Decl->TypeForDecl = newType;
2411 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002412 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002413 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002414
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002415 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002416}
2417
Chris Lattner32d920b2007-01-26 02:01:53 +00002418/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002419/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002420QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002421ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2422 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002423 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002424
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002425 if (Canonical.isNull())
2426 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002427 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002428 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002429 Decl->TypeForDecl = newType;
2430 Types.push_back(newType);
2431 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002432}
2433
Jay Foad39c79802011-01-12 09:06:06 +00002434QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002435 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2436
Douglas Gregorec9fd132012-01-14 16:38:05 +00002437 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002438 if (PrevDecl->TypeForDecl)
2439 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2440
John McCall424cec92011-01-19 06:33:43 +00002441 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2442 Decl->TypeForDecl = newType;
2443 Types.push_back(newType);
2444 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002445}
2446
Jay Foad39c79802011-01-12 09:06:06 +00002447QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002448 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2449
Douglas Gregorec9fd132012-01-14 16:38:05 +00002450 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002451 if (PrevDecl->TypeForDecl)
2452 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2453
John McCall424cec92011-01-19 06:33:43 +00002454 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2455 Decl->TypeForDecl = newType;
2456 Types.push_back(newType);
2457 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002458}
2459
John McCall81904512011-01-06 01:58:22 +00002460QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2461 QualType modifiedType,
2462 QualType equivalentType) {
2463 llvm::FoldingSetNodeID id;
2464 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2465
2466 void *insertPos = 0;
2467 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2468 if (type) return QualType(type, 0);
2469
2470 QualType canon = getCanonicalType(equivalentType);
2471 type = new (*this, TypeAlignment)
2472 AttributedType(canon, attrKind, modifiedType, equivalentType);
2473
2474 Types.push_back(type);
2475 AttributedTypes.InsertNode(type, insertPos);
2476
2477 return QualType(type, 0);
2478}
2479
2480
John McCallcebee162009-10-18 09:09:24 +00002481/// \brief Retrieve a substitution-result type.
2482QualType
2483ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002484 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002485 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002486 && "replacement types must always be canonical");
2487
2488 llvm::FoldingSetNodeID ID;
2489 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2490 void *InsertPos = 0;
2491 SubstTemplateTypeParmType *SubstParm
2492 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2493
2494 if (!SubstParm) {
2495 SubstParm = new (*this, TypeAlignment)
2496 SubstTemplateTypeParmType(Parm, Replacement);
2497 Types.push_back(SubstParm);
2498 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2499 }
2500
2501 return QualType(SubstParm, 0);
2502}
2503
Douglas Gregorada4b792011-01-14 02:55:32 +00002504/// \brief Retrieve a
2505QualType ASTContext::getSubstTemplateTypeParmPackType(
2506 const TemplateTypeParmType *Parm,
2507 const TemplateArgument &ArgPack) {
2508#ifndef NDEBUG
2509 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2510 PEnd = ArgPack.pack_end();
2511 P != PEnd; ++P) {
2512 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2513 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2514 }
2515#endif
2516
2517 llvm::FoldingSetNodeID ID;
2518 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2519 void *InsertPos = 0;
2520 if (SubstTemplateTypeParmPackType *SubstParm
2521 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2522 return QualType(SubstParm, 0);
2523
2524 QualType Canon;
2525 if (!Parm->isCanonicalUnqualified()) {
2526 Canon = getCanonicalType(QualType(Parm, 0));
2527 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2528 ArgPack);
2529 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2530 }
2531
2532 SubstTemplateTypeParmPackType *SubstParm
2533 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2534 ArgPack);
2535 Types.push_back(SubstParm);
2536 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2537 return QualType(SubstParm, 0);
2538}
2539
Douglas Gregoreff93e02009-02-05 23:33:38 +00002540/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002541/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002542/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002543QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002544 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002545 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002546 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002547 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002548 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002549 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002550 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2551
2552 if (TypeParm)
2553 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002554
Chandler Carruth08836322011-05-01 00:51:33 +00002555 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002556 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002557 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002558
2559 TemplateTypeParmType *TypeCheck
2560 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2561 assert(!TypeCheck && "Template type parameter canonical type broken");
2562 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002563 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002564 TypeParm = new (*this, TypeAlignment)
2565 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002566
2567 Types.push_back(TypeParm);
2568 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2569
2570 return QualType(TypeParm, 0);
2571}
2572
John McCalle78aac42010-03-10 03:28:59 +00002573TypeSourceInfo *
2574ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2575 SourceLocation NameLoc,
2576 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002577 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002578 assert(!Name.getAsDependentTemplateName() &&
2579 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002580 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002581
2582 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2583 TemplateSpecializationTypeLoc TL
2584 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002585 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002586 TL.setTemplateNameLoc(NameLoc);
2587 TL.setLAngleLoc(Args.getLAngleLoc());
2588 TL.setRAngleLoc(Args.getRAngleLoc());
2589 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2590 TL.setArgLocInfo(i, Args[i].getLocInfo());
2591 return DI;
2592}
2593
Mike Stump11289f42009-09-09 15:08:12 +00002594QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002595ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002596 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002597 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002598 assert(!Template.getAsDependentTemplateName() &&
2599 "No dependent template names here!");
2600
John McCall6b51f282009-11-23 01:53:49 +00002601 unsigned NumArgs = Args.size();
2602
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002603 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002604 ArgVec.reserve(NumArgs);
2605 for (unsigned i = 0; i != NumArgs; ++i)
2606 ArgVec.push_back(Args[i].getArgument());
2607
John McCall2408e322010-04-27 00:57:59 +00002608 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002609 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002610}
2611
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002612#ifndef NDEBUG
2613static bool hasAnyPackExpansions(const TemplateArgument *Args,
2614 unsigned NumArgs) {
2615 for (unsigned I = 0; I != NumArgs; ++I)
2616 if (Args[I].isPackExpansion())
2617 return true;
2618
2619 return true;
2620}
2621#endif
2622
John McCall0ad16662009-10-29 08:12:44 +00002623QualType
2624ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002625 const TemplateArgument *Args,
2626 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002627 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002628 assert(!Template.getAsDependentTemplateName() &&
2629 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002630 // Look through qualified template names.
2631 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2632 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002633
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002634 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002635 Template.getAsTemplateDecl() &&
2636 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002637 QualType CanonType;
2638 if (!Underlying.isNull())
2639 CanonType = getCanonicalType(Underlying);
2640 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002641 // We can get here with an alias template when the specialization contains
2642 // a pack expansion that does not match up with a parameter pack.
2643 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2644 "Caller must compute aliased type");
2645 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002646 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2647 NumArgs);
2648 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002649
Douglas Gregora8e02e72009-07-28 23:00:59 +00002650 // Allocate the (non-canonical) template specialization type, but don't
2651 // try to unique it: these types typically have location information that
2652 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002653 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2654 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002655 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002656 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002657 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002658 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2659 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002660
Douglas Gregor8bf42052009-02-09 18:46:07 +00002661 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002662 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002663}
2664
Mike Stump11289f42009-09-09 15:08:12 +00002665QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002666ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2667 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002668 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002669 assert(!Template.getAsDependentTemplateName() &&
2670 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002671
Douglas Gregore29139c2011-03-03 17:04:51 +00002672 // Look through qualified template names.
2673 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2674 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002675
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002676 // Build the canonical template specialization type.
2677 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002678 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002679 CanonArgs.reserve(NumArgs);
2680 for (unsigned I = 0; I != NumArgs; ++I)
2681 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2682
2683 // Determine whether this canonical template specialization type already
2684 // exists.
2685 llvm::FoldingSetNodeID ID;
2686 TemplateSpecializationType::Profile(ID, CanonTemplate,
2687 CanonArgs.data(), NumArgs, *this);
2688
2689 void *InsertPos = 0;
2690 TemplateSpecializationType *Spec
2691 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2692
2693 if (!Spec) {
2694 // Allocate a new canonical template specialization type.
2695 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2696 sizeof(TemplateArgument) * NumArgs),
2697 TypeAlignment);
2698 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2699 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002700 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002701 Types.push_back(Spec);
2702 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2703 }
2704
2705 assert(Spec->isDependentType() &&
2706 "Non-dependent template-id type must have a canonical type");
2707 return QualType(Spec, 0);
2708}
2709
2710QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002711ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2712 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002713 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002714 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002715 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002716
2717 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002718 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002719 if (T)
2720 return QualType(T, 0);
2721
Douglas Gregorc42075a2010-02-04 18:10:26 +00002722 QualType Canon = NamedType;
2723 if (!Canon.isCanonical()) {
2724 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002725 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2726 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002727 (void)CheckT;
2728 }
2729
Abramo Bagnara6150c882010-05-11 21:36:43 +00002730 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002731 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002732 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002733 return QualType(T, 0);
2734}
2735
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002736QualType
Jay Foad39c79802011-01-12 09:06:06 +00002737ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002738 llvm::FoldingSetNodeID ID;
2739 ParenType::Profile(ID, InnerType);
2740
2741 void *InsertPos = 0;
2742 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2743 if (T)
2744 return QualType(T, 0);
2745
2746 QualType Canon = InnerType;
2747 if (!Canon.isCanonical()) {
2748 Canon = getCanonicalType(InnerType);
2749 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 assert(!CheckT && "Paren canonical type broken");
2751 (void)CheckT;
2752 }
2753
2754 T = new (*this) ParenType(InnerType, Canon);
2755 Types.push_back(T);
2756 ParenTypes.InsertNode(T, InsertPos);
2757 return QualType(T, 0);
2758}
2759
Douglas Gregor02085352010-03-31 20:19:30 +00002760QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2761 NestedNameSpecifier *NNS,
2762 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002763 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002764 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2765
2766 if (Canon.isNull()) {
2767 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002768 ElaboratedTypeKeyword CanonKeyword = Keyword;
2769 if (Keyword == ETK_None)
2770 CanonKeyword = ETK_Typename;
2771
2772 if (CanonNNS != NNS || CanonKeyword != Keyword)
2773 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002774 }
2775
2776 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002777 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002778
2779 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002780 DependentNameType *T
2781 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002782 if (T)
2783 return QualType(T, 0);
2784
Douglas Gregor02085352010-03-31 20:19:30 +00002785 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002786 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002787 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002788 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002789}
2790
Mike Stump11289f42009-09-09 15:08:12 +00002791QualType
John McCallc392f372010-06-11 00:33:02 +00002792ASTContext::getDependentTemplateSpecializationType(
2793 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002794 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002795 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002796 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002797 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002798 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002799 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2800 ArgCopy.push_back(Args[I].getArgument());
2801 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2802 ArgCopy.size(),
2803 ArgCopy.data());
2804}
2805
2806QualType
2807ASTContext::getDependentTemplateSpecializationType(
2808 ElaboratedTypeKeyword Keyword,
2809 NestedNameSpecifier *NNS,
2810 const IdentifierInfo *Name,
2811 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002812 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002813 assert((!NNS || NNS->isDependent()) &&
2814 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002815
Douglas Gregorc42075a2010-02-04 18:10:26 +00002816 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002817 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2818 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002819
2820 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002821 DependentTemplateSpecializationType *T
2822 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002823 if (T)
2824 return QualType(T, 0);
2825
John McCallc392f372010-06-11 00:33:02 +00002826 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002827
John McCallc392f372010-06-11 00:33:02 +00002828 ElaboratedTypeKeyword CanonKeyword = Keyword;
2829 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2830
2831 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002832 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002833 for (unsigned I = 0; I != NumArgs; ++I) {
2834 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2835 if (!CanonArgs[I].structurallyEquals(Args[I]))
2836 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002837 }
2838
John McCallc392f372010-06-11 00:33:02 +00002839 QualType Canon;
2840 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2841 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2842 Name, NumArgs,
2843 CanonArgs.data());
2844
2845 // Find the insert position again.
2846 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2847 }
2848
2849 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2850 sizeof(TemplateArgument) * NumArgs),
2851 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002852 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002853 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002854 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002855 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002856 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002857}
2858
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002859QualType ASTContext::getPackExpansionType(QualType Pattern,
2860 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002861 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002862 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002863
2864 assert(Pattern->containsUnexpandedParameterPack() &&
2865 "Pack expansions must expand one or more parameter packs");
2866 void *InsertPos = 0;
2867 PackExpansionType *T
2868 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2869 if (T)
2870 return QualType(T, 0);
2871
2872 QualType Canon;
2873 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002874 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002875
2876 // Find the insert position again.
2877 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2878 }
2879
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002880 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002881 Types.push_back(T);
2882 PackExpansionTypes.InsertNode(T, InsertPos);
2883 return QualType(T, 0);
2884}
2885
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002886/// CmpProtocolNames - Comparison predicate for sorting protocols
2887/// alphabetically.
2888static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2889 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002890 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002891}
2892
John McCall8b07ec22010-05-15 11:32:37 +00002893static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002894 unsigned NumProtocols) {
2895 if (NumProtocols == 0) return true;
2896
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002897 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2898 return false;
2899
John McCallfc93cf92009-10-22 22:37:11 +00002900 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002901 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2902 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002903 return false;
2904 return true;
2905}
2906
2907static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002908 unsigned &NumProtocols) {
2909 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002910
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002911 // Sort protocols, keyed by name.
2912 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2913
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002914 // Canonicalize.
2915 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2916 Protocols[I] = Protocols[I]->getCanonicalDecl();
2917
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002918 // Remove duplicates.
2919 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2920 NumProtocols = ProtocolsEnd-Protocols;
2921}
2922
John McCall8b07ec22010-05-15 11:32:37 +00002923QualType ASTContext::getObjCObjectType(QualType BaseType,
2924 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002925 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002926 // If the base type is an interface and there aren't any protocols
2927 // to add, then the interface type will do just fine.
2928 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2929 return BaseType;
2930
2931 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002932 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002933 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002934 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002935 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2936 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002937
John McCall8b07ec22010-05-15 11:32:37 +00002938 // Build the canonical type, which has the canonical base type and
2939 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002940 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002941 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2942 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2943 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002944 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002945 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002946 unsigned UniqueCount = NumProtocols;
2947
John McCallfc93cf92009-10-22 22:37:11 +00002948 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002949 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2950 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002951 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002952 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2953 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002954 }
2955
2956 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002957 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2958 }
2959
2960 unsigned Size = sizeof(ObjCObjectTypeImpl);
2961 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2962 void *Mem = Allocate(Size, TypeAlignment);
2963 ObjCObjectTypeImpl *T =
2964 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2965
2966 Types.push_back(T);
2967 ObjCObjectTypes.InsertNode(T, InsertPos);
2968 return QualType(T, 0);
2969}
2970
2971/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2972/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002973QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002974 llvm::FoldingSetNodeID ID;
2975 ObjCObjectPointerType::Profile(ID, ObjectT);
2976
2977 void *InsertPos = 0;
2978 if (ObjCObjectPointerType *QT =
2979 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2980 return QualType(QT, 0);
2981
2982 // Find the canonical object type.
2983 QualType Canonical;
2984 if (!ObjectT.isCanonical()) {
2985 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2986
2987 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002988 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2989 }
2990
Douglas Gregorf85bee62010-02-08 22:59:26 +00002991 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002992 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2993 ObjCObjectPointerType *QType =
2994 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002995
Steve Narofffb4330f2009-06-17 22:40:22 +00002996 Types.push_back(QType);
2997 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002998 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002999}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003000
Douglas Gregor1c283312010-08-11 12:19:30 +00003001/// getObjCInterfaceType - Return the unique reference to the type for the
3002/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003003QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3004 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003005 if (Decl->TypeForDecl)
3006 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003007
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003008 if (PrevDecl) {
3009 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3010 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3011 return QualType(PrevDecl->TypeForDecl, 0);
3012 }
3013
Douglas Gregor7671e532011-12-16 16:34:57 +00003014 // Prefer the definition, if there is one.
3015 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3016 Decl = Def;
3017
Douglas Gregor1c283312010-08-11 12:19:30 +00003018 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3019 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3020 Decl->TypeForDecl = T;
3021 Types.push_back(T);
3022 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003023}
3024
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003025/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3026/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003027/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003028/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003029/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003030QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003031 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003032 if (tofExpr->isTypeDependent()) {
3033 llvm::FoldingSetNodeID ID;
3034 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003035
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003036 void *InsertPos = 0;
3037 DependentTypeOfExprType *Canon
3038 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3039 if (Canon) {
3040 // We already have a "canonical" version of an identical, dependent
3041 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003042 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003043 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003044 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003045 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003046 Canon
3047 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003048 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3049 toe = Canon;
3050 }
3051 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003052 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003053 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003054 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003055 Types.push_back(toe);
3056 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003057}
3058
Steve Naroffa773cd52007-08-01 18:02:17 +00003059/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3060/// TypeOfType AST's. The only motivation to unique these nodes would be
3061/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003062/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003063/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003064QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003065 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003066 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003067 Types.push_back(tot);
3068 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003069}
3070
Anders Carlssonad6bd352009-06-24 21:24:56 +00003071
Anders Carlsson81df7b82009-06-24 19:06:50 +00003072/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3073/// DecltypeType AST's. The only motivation to unique these nodes would be
3074/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003075/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003076/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003077QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003078 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003079
3080 // C++0x [temp.type]p2:
3081 // If an expression e involves a template parameter, decltype(e) denotes a
3082 // unique dependent type. Two such decltype-specifiers refer to the same
3083 // type only if their expressions are equivalent (14.5.6.1).
3084 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003085 llvm::FoldingSetNodeID ID;
3086 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003087
Douglas Gregora21f6c32009-07-30 23:36:40 +00003088 void *InsertPos = 0;
3089 DependentDecltypeType *Canon
3090 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3091 if (Canon) {
3092 // We already have a "canonical" version of an equivalent, dependent
3093 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003094 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003095 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003096 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003097 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003098 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003099 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3100 dt = Canon;
3101 }
3102 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003103 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3104 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003105 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003106 Types.push_back(dt);
3107 return QualType(dt, 0);
3108}
3109
Alexis Hunte852b102011-05-24 22:41:36 +00003110/// getUnaryTransformationType - We don't unique these, since the memory
3111/// savings are minimal and these are rare.
3112QualType ASTContext::getUnaryTransformType(QualType BaseType,
3113 QualType UnderlyingType,
3114 UnaryTransformType::UTTKind Kind)
3115 const {
3116 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003117 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3118 Kind,
3119 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003120 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003121 Types.push_back(Ty);
3122 return QualType(Ty, 0);
3123}
3124
Richard Smithb2bc2e62011-02-21 20:05:19 +00003125/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003126QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003127 void *InsertPos = 0;
3128 if (!DeducedType.isNull()) {
3129 // Look in the folding set for an existing type.
3130 llvm::FoldingSetNodeID ID;
3131 AutoType::Profile(ID, DeducedType);
3132 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3133 return QualType(AT, 0);
3134 }
3135
3136 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3137 Types.push_back(AT);
3138 if (InsertPos)
3139 AutoTypes.InsertNode(AT, InsertPos);
3140 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003141}
3142
Eli Friedman0dfb8892011-10-06 23:00:33 +00003143/// getAtomicType - Return the uniqued reference to the atomic type for
3144/// the given value type.
3145QualType ASTContext::getAtomicType(QualType T) const {
3146 // Unique pointers, to guarantee there is only one pointer of a particular
3147 // structure.
3148 llvm::FoldingSetNodeID ID;
3149 AtomicType::Profile(ID, T);
3150
3151 void *InsertPos = 0;
3152 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3153 return QualType(AT, 0);
3154
3155 // If the atomic value type isn't canonical, this won't be a canonical type
3156 // either, so fill in the canonical type field.
3157 QualType Canonical;
3158 if (!T.isCanonical()) {
3159 Canonical = getAtomicType(getCanonicalType(T));
3160
3161 // Get the new insert position for the node we care about.
3162 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3163 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3164 }
3165 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3166 Types.push_back(New);
3167 AtomicTypes.InsertNode(New, InsertPos);
3168 return QualType(New, 0);
3169}
3170
Richard Smith02e85f32011-04-14 22:09:26 +00003171/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3172QualType ASTContext::getAutoDeductType() const {
3173 if (AutoDeductTy.isNull())
3174 AutoDeductTy = getAutoType(QualType());
3175 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3176 return AutoDeductTy;
3177}
3178
3179/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3180QualType ASTContext::getAutoRRefDeductType() const {
3181 if (AutoRRefDeductTy.isNull())
3182 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3183 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3184 return AutoRRefDeductTy;
3185}
3186
Chris Lattnerfb072462007-01-23 05:45:31 +00003187/// getTagDeclType - Return the unique reference to the type for the
3188/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003189QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003190 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003191 // FIXME: What is the design on getTagDeclType when it requires casting
3192 // away const? mutable?
3193 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003194}
3195
Mike Stump11289f42009-09-09 15:08:12 +00003196/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3197/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3198/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003199CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003200 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003201}
Chris Lattnerfb072462007-01-23 05:45:31 +00003202
Hans Wennborg27541db2011-10-27 08:29:09 +00003203/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3204CanQualType ASTContext::getIntMaxType() const {
3205 return getFromTargetType(Target->getIntMaxType());
3206}
3207
3208/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3209CanQualType ASTContext::getUIntMaxType() const {
3210 return getFromTargetType(Target->getUIntMaxType());
3211}
3212
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003213/// getSignedWCharType - Return the type of "signed wchar_t".
3214/// Used when in C++, as a GCC extension.
3215QualType ASTContext::getSignedWCharType() const {
3216 // FIXME: derive from "Target" ?
3217 return WCharTy;
3218}
3219
3220/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3221/// Used when in C++, as a GCC extension.
3222QualType ASTContext::getUnsignedWCharType() const {
3223 // FIXME: derive from "Target" ?
3224 return UnsignedIntTy;
3225}
3226
Hans Wennborg27541db2011-10-27 08:29:09 +00003227/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003228/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3229QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003230 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003231}
3232
Chris Lattnera21ad802008-04-02 05:18:44 +00003233//===----------------------------------------------------------------------===//
3234// Type Operators
3235//===----------------------------------------------------------------------===//
3236
Jay Foad39c79802011-01-12 09:06:06 +00003237CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003238 // Push qualifiers into arrays, and then discard any remaining
3239 // qualifiers.
3240 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003241 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003242 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003243 QualType Result;
3244 if (isa<ArrayType>(Ty)) {
3245 Result = getArrayDecayedType(QualType(Ty,0));
3246 } else if (isa<FunctionType>(Ty)) {
3247 Result = getPointerType(QualType(Ty, 0));
3248 } else {
3249 Result = QualType(Ty, 0);
3250 }
3251
3252 return CanQualType::CreateUnsafe(Result);
3253}
3254
John McCall6c9dd522011-01-18 07:41:22 +00003255QualType ASTContext::getUnqualifiedArrayType(QualType type,
3256 Qualifiers &quals) {
3257 SplitQualType splitType = type.getSplitUnqualifiedType();
3258
3259 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3260 // the unqualified desugared type and then drops it on the floor.
3261 // We then have to strip that sugar back off with
3262 // getUnqualifiedDesugaredType(), which is silly.
3263 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003264 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003265
3266 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003267 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003268 quals = splitType.Quals;
3269 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003270 }
3271
John McCall6c9dd522011-01-18 07:41:22 +00003272 // Otherwise, recurse on the array's element type.
3273 QualType elementType = AT->getElementType();
3274 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3275
3276 // If that didn't change the element type, AT has no qualifiers, so we
3277 // can just use the results in splitType.
3278 if (elementType == unqualElementType) {
3279 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003280 quals = splitType.Quals;
3281 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003282 }
3283
3284 // Otherwise, add in the qualifiers from the outermost type, then
3285 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003286 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003287
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003288 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003289 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003290 CAT->getSizeModifier(), 0);
3291 }
3292
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003293 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003294 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003295 }
3296
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003297 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003298 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003299 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003300 VAT->getSizeModifier(),
3301 VAT->getIndexTypeCVRQualifiers(),
3302 VAT->getBracketsRange());
3303 }
3304
3305 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003306 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003307 DSAT->getSizeModifier(), 0,
3308 SourceRange());
3309}
3310
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003311/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3312/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3313/// they point to and return true. If T1 and T2 aren't pointer types
3314/// or pointer-to-member types, or if they are not similar at this
3315/// level, returns false and leaves T1 and T2 unchanged. Top-level
3316/// qualifiers on T1 and T2 are ignored. This function will typically
3317/// be called in a loop that successively "unwraps" pointer and
3318/// pointer-to-member types to compare them at each level.
3319bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3320 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3321 *T2PtrType = T2->getAs<PointerType>();
3322 if (T1PtrType && T2PtrType) {
3323 T1 = T1PtrType->getPointeeType();
3324 T2 = T2PtrType->getPointeeType();
3325 return true;
3326 }
3327
3328 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3329 *T2MPType = T2->getAs<MemberPointerType>();
3330 if (T1MPType && T2MPType &&
3331 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3332 QualType(T2MPType->getClass(), 0))) {
3333 T1 = T1MPType->getPointeeType();
3334 T2 = T2MPType->getPointeeType();
3335 return true;
3336 }
3337
David Blaikiebbafb8a2012-03-11 07:00:24 +00003338 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003339 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3340 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3341 if (T1OPType && T2OPType) {
3342 T1 = T1OPType->getPointeeType();
3343 T2 = T2OPType->getPointeeType();
3344 return true;
3345 }
3346 }
3347
3348 // FIXME: Block pointers, too?
3349
3350 return false;
3351}
3352
Jay Foad39c79802011-01-12 09:06:06 +00003353DeclarationNameInfo
3354ASTContext::getNameForTemplate(TemplateName Name,
3355 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003356 switch (Name.getKind()) {
3357 case TemplateName::QualifiedTemplate:
3358 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003359 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003360 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3361 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003362
John McCalld9dfe3a2011-06-30 08:33:18 +00003363 case TemplateName::OverloadedTemplate: {
3364 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3365 // DNInfo work in progress: CHECKME: what about DNLoc?
3366 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3367 }
3368
3369 case TemplateName::DependentTemplate: {
3370 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003371 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003372 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003373 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3374 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003375 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003376 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3377 // DNInfo work in progress: FIXME: source locations?
3378 DeclarationNameLoc DNLoc;
3379 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3380 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3381 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003382 }
3383 }
3384
John McCalld9dfe3a2011-06-30 08:33:18 +00003385 case TemplateName::SubstTemplateTemplateParm: {
3386 SubstTemplateTemplateParmStorage *subst
3387 = Name.getAsSubstTemplateTemplateParm();
3388 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3389 NameLoc);
3390 }
3391
3392 case TemplateName::SubstTemplateTemplateParmPack: {
3393 SubstTemplateTemplateParmPackStorage *subst
3394 = Name.getAsSubstTemplateTemplateParmPack();
3395 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3396 NameLoc);
3397 }
3398 }
3399
3400 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003401}
3402
Jay Foad39c79802011-01-12 09:06:06 +00003403TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003404 switch (Name.getKind()) {
3405 case TemplateName::QualifiedTemplate:
3406 case TemplateName::Template: {
3407 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003408 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003409 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003410 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3411
3412 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003413 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003414 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003415
John McCalld9dfe3a2011-06-30 08:33:18 +00003416 case TemplateName::OverloadedTemplate:
3417 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003418
John McCalld9dfe3a2011-06-30 08:33:18 +00003419 case TemplateName::DependentTemplate: {
3420 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3421 assert(DTN && "Non-dependent template names must refer to template decls.");
3422 return DTN->CanonicalTemplateName;
3423 }
3424
3425 case TemplateName::SubstTemplateTemplateParm: {
3426 SubstTemplateTemplateParmStorage *subst
3427 = Name.getAsSubstTemplateTemplateParm();
3428 return getCanonicalTemplateName(subst->getReplacement());
3429 }
3430
3431 case TemplateName::SubstTemplateTemplateParmPack: {
3432 SubstTemplateTemplateParmPackStorage *subst
3433 = Name.getAsSubstTemplateTemplateParmPack();
3434 TemplateTemplateParmDecl *canonParameter
3435 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3436 TemplateArgument canonArgPack
3437 = getCanonicalTemplateArgument(subst->getArgumentPack());
3438 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3439 }
3440 }
3441
3442 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003443}
3444
Douglas Gregoradee3e32009-11-11 23:06:43 +00003445bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3446 X = getCanonicalTemplateName(X);
3447 Y = getCanonicalTemplateName(Y);
3448 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3449}
3450
Mike Stump11289f42009-09-09 15:08:12 +00003451TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003452ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003453 switch (Arg.getKind()) {
3454 case TemplateArgument::Null:
3455 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003456
Douglas Gregora8e02e72009-07-28 23:00:59 +00003457 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003458 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003459
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003460 case TemplateArgument::Declaration: {
3461 if (Decl *D = Arg.getAsDecl())
3462 return TemplateArgument(D->getCanonicalDecl());
3463 return TemplateArgument((Decl*)0);
3464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003466 case TemplateArgument::Template:
3467 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003468
3469 case TemplateArgument::TemplateExpansion:
3470 return TemplateArgument(getCanonicalTemplateName(
3471 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003472 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003473
Douglas Gregora8e02e72009-07-28 23:00:59 +00003474 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003475 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003476
Douglas Gregora8e02e72009-07-28 23:00:59 +00003477 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003478 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003479
Douglas Gregora8e02e72009-07-28 23:00:59 +00003480 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003481 if (Arg.pack_size() == 0)
3482 return Arg;
3483
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003484 TemplateArgument *CanonArgs
3485 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003486 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003487 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003488 AEnd = Arg.pack_end();
3489 A != AEnd; (void)++A, ++Idx)
3490 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003491
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003492 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003493 }
3494 }
3495
3496 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003497 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003498}
3499
Douglas Gregor333489b2009-03-27 23:10:48 +00003500NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003501ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003502 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003503 return 0;
3504
3505 switch (NNS->getKind()) {
3506 case NestedNameSpecifier::Identifier:
3507 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003508 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003509 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3510 NNS->getAsIdentifier());
3511
3512 case NestedNameSpecifier::Namespace:
3513 // A namespace is canonical; build a nested-name-specifier with
3514 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003515 return NestedNameSpecifier::Create(*this, 0,
3516 NNS->getAsNamespace()->getOriginalNamespace());
3517
3518 case NestedNameSpecifier::NamespaceAlias:
3519 // A namespace is canonical; build a nested-name-specifier with
3520 // this namespace and no prefix.
3521 return NestedNameSpecifier::Create(*this, 0,
3522 NNS->getAsNamespaceAlias()->getNamespace()
3523 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003524
3525 case NestedNameSpecifier::TypeSpec:
3526 case NestedNameSpecifier::TypeSpecWithTemplate: {
3527 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003528
3529 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3530 // break it apart into its prefix and identifier, then reconsititute those
3531 // as the canonical nested-name-specifier. This is required to canonicalize
3532 // a dependent nested-name-specifier involving typedefs of dependent-name
3533 // types, e.g.,
3534 // typedef typename T::type T1;
3535 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003536 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3537 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003538 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003539
Eli Friedman5358a0a2012-03-03 04:09:56 +00003540 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3541 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3542 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003543 return NestedNameSpecifier::Create(*this, 0, false,
3544 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003545 }
3546
3547 case NestedNameSpecifier::Global:
3548 // The global specifier is canonical and unique.
3549 return NNS;
3550 }
3551
David Blaikie8a40f702012-01-17 06:56:22 +00003552 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003553}
3554
Chris Lattner7adf0762008-08-04 07:31:14 +00003555
Jay Foad39c79802011-01-12 09:06:06 +00003556const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003557 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003558 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003559 // Handle the common positive case fast.
3560 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3561 return AT;
3562 }
Mike Stump11289f42009-09-09 15:08:12 +00003563
John McCall8ccfcb52009-09-24 19:53:00 +00003564 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003565 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003566 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003567
John McCall8ccfcb52009-09-24 19:53:00 +00003568 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003569 // implements C99 6.7.3p8: "If the specification of an array type includes
3570 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003571
Chris Lattner7adf0762008-08-04 07:31:14 +00003572 // If we get here, we either have type qualifiers on the type, or we have
3573 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003574 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003575
John McCall33ddac02011-01-19 10:06:00 +00003576 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003577 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003578
Chris Lattner7adf0762008-08-04 07:31:14 +00003579 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003580 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003581 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003582 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003583
Chris Lattner7adf0762008-08-04 07:31:14 +00003584 // Otherwise, we have an array and we have qualifiers on it. Push the
3585 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003586 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003587
Chris Lattner7adf0762008-08-04 07:31:14 +00003588 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3589 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3590 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003591 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003592 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3593 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3594 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003595 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003596
Mike Stump11289f42009-09-09 15:08:12 +00003597 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003598 = dyn_cast<DependentSizedArrayType>(ATy))
3599 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003600 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003601 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003602 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003603 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003604 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003605
Chris Lattner7adf0762008-08-04 07:31:14 +00003606 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003607 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003608 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003609 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003610 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003611 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003612}
3613
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003614QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003615 // C99 6.7.5.3p7:
3616 // A declaration of a parameter as "array of type" shall be
3617 // adjusted to "qualified pointer to type", where the type
3618 // qualifiers (if any) are those specified within the [ and ] of
3619 // the array type derivation.
3620 if (T->isArrayType())
3621 return getArrayDecayedType(T);
3622
3623 // C99 6.7.5.3p8:
3624 // A declaration of a parameter as "function returning type"
3625 // shall be adjusted to "pointer to function returning type", as
3626 // in 6.3.2.1.
3627 if (T->isFunctionType())
3628 return getPointerType(T);
3629
3630 return T;
3631}
3632
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003633QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003634 T = getVariableArrayDecayedType(T);
3635 T = getAdjustedParameterType(T);
3636 return T.getUnqualifiedType();
3637}
3638
Chris Lattnera21ad802008-04-02 05:18:44 +00003639/// getArrayDecayedType - Return the properly qualified result of decaying the
3640/// specified array type to a pointer. This operation is non-trivial when
3641/// handling typedefs etc. The canonical type of "T" must be an array type,
3642/// this returns a pointer to a properly qualified element of the array.
3643///
3644/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003645QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003646 // Get the element type with 'getAsArrayType' so that we don't lose any
3647 // typedefs in the element type of the array. This also handles propagation
3648 // of type qualifiers from the array type into the element type if present
3649 // (C99 6.7.3p8).
3650 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3651 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003652
Chris Lattner7adf0762008-08-04 07:31:14 +00003653 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003654
3655 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003656 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003657}
3658
John McCall33ddac02011-01-19 10:06:00 +00003659QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3660 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003661}
3662
John McCall33ddac02011-01-19 10:06:00 +00003663QualType ASTContext::getBaseElementType(QualType type) const {
3664 Qualifiers qs;
3665 while (true) {
3666 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003667 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003668 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003669
John McCall33ddac02011-01-19 10:06:00 +00003670 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003671 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003672 }
Mike Stump11289f42009-09-09 15:08:12 +00003673
John McCall33ddac02011-01-19 10:06:00 +00003674 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003675}
3676
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003677/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003678uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003679ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3680 uint64_t ElementCount = 1;
3681 do {
3682 ElementCount *= CA->getSize().getZExtValue();
3683 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3684 } while (CA);
3685 return ElementCount;
3686}
3687
Steve Naroff0af91202007-04-27 21:51:21 +00003688/// getFloatingRank - Return a relative rank for floating point types.
3689/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003690static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003691 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003692 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003693
John McCall9dd450b2009-09-21 23:43:11 +00003694 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3695 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003696 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003697 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003698 case BuiltinType::Float: return FloatRank;
3699 case BuiltinType::Double: return DoubleRank;
3700 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003701 }
3702}
3703
Mike Stump11289f42009-09-09 15:08:12 +00003704/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3705/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003706/// 'typeDomain' is a real floating point or complex type.
3707/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003708QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3709 QualType Domain) const {
3710 FloatingRank EltRank = getFloatingRank(Size);
3711 if (Domain->isComplexType()) {
3712 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003713 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003714 case FloatRank: return FloatComplexTy;
3715 case DoubleRank: return DoubleComplexTy;
3716 case LongDoubleRank: return LongDoubleComplexTy;
3717 }
Steve Naroff0af91202007-04-27 21:51:21 +00003718 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003719
3720 assert(Domain->isRealFloatingType() && "Unknown domain!");
3721 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003722 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003723 case FloatRank: return FloatTy;
3724 case DoubleRank: return DoubleTy;
3725 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003726 }
David Blaikief47fa302012-01-17 02:30:50 +00003727 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003728}
3729
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003730/// getFloatingTypeOrder - Compare the rank of the two specified floating
3731/// point types, ignoring the domain of the type (i.e. 'double' ==
3732/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003733/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003734int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003735 FloatingRank LHSR = getFloatingRank(LHS);
3736 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003737
Chris Lattnerb90739d2008-04-06 23:38:49 +00003738 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003739 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003740 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003741 return 1;
3742 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003743}
3744
Chris Lattner76a00cf2008-04-06 22:59:24 +00003745/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3746/// routine will assert if passed a built-in type that isn't an integer or enum,
3747/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003748unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003749 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003750
Chris Lattner76a00cf2008-04-06 22:59:24 +00003751 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003752 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003753 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003754 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003755 case BuiltinType::Char_S:
3756 case BuiltinType::Char_U:
3757 case BuiltinType::SChar:
3758 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003759 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003760 case BuiltinType::Short:
3761 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003762 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003763 case BuiltinType::Int:
3764 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003765 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003766 case BuiltinType::Long:
3767 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003768 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003769 case BuiltinType::LongLong:
3770 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003771 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003772 case BuiltinType::Int128:
3773 case BuiltinType::UInt128:
3774 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003775 }
3776}
3777
Eli Friedman629ffb92009-08-20 04:21:42 +00003778/// \brief Whether this is a promotable bitfield reference according
3779/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3780///
3781/// \returns the type this bit-field will promote to, or NULL if no
3782/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003783QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003784 if (E->isTypeDependent() || E->isValueDependent())
3785 return QualType();
3786
Eli Friedman629ffb92009-08-20 04:21:42 +00003787 FieldDecl *Field = E->getBitField();
3788 if (!Field)
3789 return QualType();
3790
3791 QualType FT = Field->getType();
3792
Richard Smithcaf33902011-10-10 18:28:20 +00003793 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003794 uint64_t IntSize = getTypeSize(IntTy);
3795 // GCC extension compatibility: if the bit-field size is less than or equal
3796 // to the size of int, it gets promoted no matter what its type is.
3797 // For instance, unsigned long bf : 4 gets promoted to signed int.
3798 if (BitWidth < IntSize)
3799 return IntTy;
3800
3801 if (BitWidth == IntSize)
3802 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3803
3804 // Types bigger than int are not subject to promotions, and therefore act
3805 // like the base type.
3806 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3807 // is ridiculous.
3808 return QualType();
3809}
3810
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003811/// getPromotedIntegerType - Returns the type that Promotable will
3812/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3813/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003814QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003815 assert(!Promotable.isNull());
3816 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003817 if (const EnumType *ET = Promotable->getAs<EnumType>())
3818 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003819
3820 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3821 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3822 // (3.9.1) can be converted to a prvalue of the first of the following
3823 // types that can represent all the values of its underlying type:
3824 // int, unsigned int, long int, unsigned long int, long long int, or
3825 // unsigned long long int [...]
3826 // FIXME: Is there some better way to compute this?
3827 if (BT->getKind() == BuiltinType::WChar_S ||
3828 BT->getKind() == BuiltinType::WChar_U ||
3829 BT->getKind() == BuiltinType::Char16 ||
3830 BT->getKind() == BuiltinType::Char32) {
3831 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3832 uint64_t FromSize = getTypeSize(BT);
3833 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3834 LongLongTy, UnsignedLongLongTy };
3835 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3836 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3837 if (FromSize < ToSize ||
3838 (FromSize == ToSize &&
3839 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3840 return PromoteTypes[Idx];
3841 }
3842 llvm_unreachable("char type should fit into long long");
3843 }
3844 }
3845
3846 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003847 if (Promotable->isSignedIntegerType())
3848 return IntTy;
3849 uint64_t PromotableSize = getTypeSize(Promotable);
3850 uint64_t IntSize = getTypeSize(IntTy);
3851 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3852 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3853}
3854
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003855/// \brief Recurses in pointer/array types until it finds an objc retainable
3856/// type and returns its ownership.
3857Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3858 while (!T.isNull()) {
3859 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3860 return T.getObjCLifetime();
3861 if (T->isArrayType())
3862 T = getBaseElementType(T);
3863 else if (const PointerType *PT = T->getAs<PointerType>())
3864 T = PT->getPointeeType();
3865 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003866 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003867 else
3868 break;
3869 }
3870
3871 return Qualifiers::OCL_None;
3872}
3873
Mike Stump11289f42009-09-09 15:08:12 +00003874/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003875/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003876/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003877int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003878 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3879 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003880 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003881
Chris Lattner76a00cf2008-04-06 22:59:24 +00003882 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3883 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003884
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003885 unsigned LHSRank = getIntegerRank(LHSC);
3886 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003887
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003888 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3889 if (LHSRank == RHSRank) return 0;
3890 return LHSRank > RHSRank ? 1 : -1;
3891 }
Mike Stump11289f42009-09-09 15:08:12 +00003892
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003893 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3894 if (LHSUnsigned) {
3895 // If the unsigned [LHS] type is larger, return it.
3896 if (LHSRank >= RHSRank)
3897 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003898
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003899 // If the signed type can represent all values of the unsigned type, it
3900 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003901 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003902 return -1;
3903 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003904
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003905 // If the unsigned [RHS] type is larger, return it.
3906 if (RHSRank >= LHSRank)
3907 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003908
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003909 // If the signed type can represent all values of the unsigned type, it
3910 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003911 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003912 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003913}
Anders Carlsson98f07902007-08-17 05:31:46 +00003914
Anders Carlsson6d417272009-11-14 21:45:58 +00003915static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003916CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3917 DeclContext *DC, IdentifierInfo *Id) {
3918 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003919 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003920 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003921 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003922 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003923}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003924
Mike Stump11289f42009-09-09 15:08:12 +00003925// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003926QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003927 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003928 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003929 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003930 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003931 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003932
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003933 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003934
Anders Carlsson98f07902007-08-17 05:31:46 +00003935 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003936 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003937 // int flags;
3938 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003939 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003940 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003941 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003942 FieldTypes[3] = LongTy;
3943
Anders Carlsson98f07902007-08-17 05:31:46 +00003944 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003945 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003946 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003947 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003948 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003949 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003950 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003951 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003952 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003953 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003954 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003955 }
3956
Douglas Gregord5058122010-02-11 01:19:42 +00003957 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003958 }
Mike Stump11289f42009-09-09 15:08:12 +00003959
Anders Carlsson98f07902007-08-17 05:31:46 +00003960 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003961}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003962
Douglas Gregor512b0772009-04-23 22:29:11 +00003963void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003964 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003965 assert(Rec && "Invalid CFConstantStringType");
3966 CFConstantStringTypeDecl = Rec->getDecl();
3967}
3968
Jay Foad39c79802011-01-12 09:06:06 +00003969QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003970 if (BlockDescriptorType)
3971 return getTagDeclType(BlockDescriptorType);
3972
3973 RecordDecl *T;
3974 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003975 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003976 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003977 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003978
3979 QualType FieldTypes[] = {
3980 UnsignedLongTy,
3981 UnsignedLongTy,
3982 };
3983
3984 const char *FieldNames[] = {
3985 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003986 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003987 };
3988
3989 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003990 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003991 SourceLocation(),
3992 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003993 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003994 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003995 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003996 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003997 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003998 T->addDecl(Field);
3999 }
4000
Douglas Gregord5058122010-02-11 01:19:42 +00004001 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004002
4003 BlockDescriptorType = T;
4004
4005 return getTagDeclType(BlockDescriptorType);
4006}
4007
Jay Foad39c79802011-01-12 09:06:06 +00004008QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004009 if (BlockDescriptorExtendedType)
4010 return getTagDeclType(BlockDescriptorExtendedType);
4011
4012 RecordDecl *T;
4013 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004014 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004015 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004016 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004017
4018 QualType FieldTypes[] = {
4019 UnsignedLongTy,
4020 UnsignedLongTy,
4021 getPointerType(VoidPtrTy),
4022 getPointerType(VoidPtrTy)
4023 };
4024
4025 const char *FieldNames[] = {
4026 "reserved",
4027 "Size",
4028 "CopyFuncPtr",
4029 "DestroyFuncPtr"
4030 };
4031
4032 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004033 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004034 SourceLocation(),
4035 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004036 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004037 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004038 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004039 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004040 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004041 T->addDecl(Field);
4042 }
4043
Douglas Gregord5058122010-02-11 01:19:42 +00004044 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004045
4046 BlockDescriptorExtendedType = T;
4047
4048 return getTagDeclType(BlockDescriptorExtendedType);
4049}
4050
Jay Foad39c79802011-01-12 09:06:06 +00004051bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004052 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004053 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004054 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004055 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4056 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004057 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004058
4059 }
4060 }
Mike Stump94967902009-10-21 18:16:27 +00004061 return false;
4062}
4063
Jay Foad39c79802011-01-12 09:06:06 +00004064QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004065ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004066 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004067 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004068 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004069 // unsigned int __flags;
4070 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004071 // void *__copy_helper; // as needed
4072 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004073 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004074 // } *
4075
Mike Stump94967902009-10-21 18:16:27 +00004076 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4077
4078 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004079 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004080 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4081 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004082 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004083 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004084 T->startDefinition();
4085 QualType Int32Ty = IntTy;
4086 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4087 QualType FieldTypes[] = {
4088 getPointerType(VoidPtrTy),
4089 getPointerType(getTagDeclType(T)),
4090 Int32Ty,
4091 Int32Ty,
4092 getPointerType(VoidPtrTy),
4093 getPointerType(VoidPtrTy),
4094 Ty
4095 };
4096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004097 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004098 "__isa",
4099 "__forwarding",
4100 "__flags",
4101 "__size",
4102 "__copy_helper",
4103 "__destroy_helper",
4104 DeclName,
4105 };
4106
4107 for (size_t i = 0; i < 7; ++i) {
4108 if (!HasCopyAndDispose && i >=4 && i <= 5)
4109 continue;
4110 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004111 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004112 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004113 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004114 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004115 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004116 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004117 T->addDecl(Field);
4118 }
4119
Douglas Gregord5058122010-02-11 01:19:42 +00004120 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004121
4122 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004123}
4124
Douglas Gregorbab8a962011-09-08 01:46:34 +00004125TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4126 if (!ObjCInstanceTypeDecl)
4127 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4128 getTranslationUnitDecl(),
4129 SourceLocation(),
4130 SourceLocation(),
4131 &Idents.get("instancetype"),
4132 getTrivialTypeSourceInfo(getObjCIdType()));
4133 return ObjCInstanceTypeDecl;
4134}
4135
Anders Carlsson18acd442007-10-29 06:33:42 +00004136// This returns true if a type has been typedefed to BOOL:
4137// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004138static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004139 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004140 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4141 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004142
Anders Carlssond8499822007-10-29 05:01:08 +00004143 return false;
4144}
4145
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004146/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004147/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004148CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004149 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4150 return CharUnits::Zero();
4151
Ken Dyck40775002010-01-11 17:06:35 +00004152 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004153
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004154 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004155 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004156 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004157 // Treat arrays as pointers, since that's how they're passed in.
4158 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004159 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004160 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004161}
4162
4163static inline
4164std::string charUnitsToString(const CharUnits &CU) {
4165 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004166}
4167
John McCall351762c2011-02-07 10:33:21 +00004168/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004169/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004170std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4171 std::string S;
4172
David Chisnall950a9512009-11-17 19:33:30 +00004173 const BlockDecl *Decl = Expr->getBlockDecl();
4174 QualType BlockTy =
4175 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4176 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004177 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004178 // Compute size of all parameters.
4179 // Start with computing size of a pointer in number of bytes.
4180 // FIXME: There might(should) be a better way of doing this computation!
4181 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004182 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4183 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004184 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004185 E = Decl->param_end(); PI != E; ++PI) {
4186 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004187 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004188 if (sz.isZero())
4189 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004190 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004191 ParmOffset += sz;
4192 }
4193 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004194 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004195 // Block pointer and offset.
4196 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004197
4198 // Argument types.
4199 ParmOffset = PtrSize;
4200 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4201 Decl->param_end(); PI != E; ++PI) {
4202 ParmVarDecl *PVDecl = *PI;
4203 QualType PType = PVDecl->getOriginalType();
4204 if (const ArrayType *AT =
4205 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4206 // Use array's original type only if it has known number of
4207 // elements.
4208 if (!isa<ConstantArrayType>(AT))
4209 PType = PVDecl->getType();
4210 } else if (PType->isFunctionType())
4211 PType = PVDecl->getType();
4212 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004213 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004214 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004215 }
John McCall351762c2011-02-07 10:33:21 +00004216
4217 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004218}
4219
Douglas Gregora9d84932011-05-27 01:19:52 +00004220bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004221 std::string& S) {
4222 // Encode result type.
4223 getObjCEncodingForType(Decl->getResultType(), S);
4224 CharUnits ParmOffset;
4225 // Compute size of all parameters.
4226 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4227 E = Decl->param_end(); PI != E; ++PI) {
4228 QualType PType = (*PI)->getType();
4229 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004230 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004231 continue;
4232
David Chisnall50e4eba2010-12-30 14:05:53 +00004233 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004234 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004235 ParmOffset += sz;
4236 }
4237 S += charUnitsToString(ParmOffset);
4238 ParmOffset = CharUnits::Zero();
4239
4240 // Argument types.
4241 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4242 E = Decl->param_end(); PI != E; ++PI) {
4243 ParmVarDecl *PVDecl = *PI;
4244 QualType PType = PVDecl->getOriginalType();
4245 if (const ArrayType *AT =
4246 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4247 // Use array's original type only if it has known number of
4248 // elements.
4249 if (!isa<ConstantArrayType>(AT))
4250 PType = PVDecl->getType();
4251 } else if (PType->isFunctionType())
4252 PType = PVDecl->getType();
4253 getObjCEncodingForType(PType, S);
4254 S += charUnitsToString(ParmOffset);
4255 ParmOffset += getObjCEncodingTypeSize(PType);
4256 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004257
4258 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004259}
4260
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004261/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4262/// method parameter or return type. If Extended, include class names and
4263/// block object types.
4264void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4265 QualType T, std::string& S,
4266 bool Extended) const {
4267 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4268 getObjCEncodingForTypeQualifier(QT, S);
4269 // Encode parameter type.
4270 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4271 true /*OutermostType*/,
4272 false /*EncodingProperty*/,
4273 false /*StructField*/,
4274 Extended /*EncodeBlockParameters*/,
4275 Extended /*EncodeClassNames*/);
4276}
4277
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004278/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004279/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004280bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004281 std::string& S,
4282 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004283 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004284 // Encode return type.
4285 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4286 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004287 // Compute size of all parameters.
4288 // Start with computing size of a pointer in number of bytes.
4289 // FIXME: There might(should) be a better way of doing this computation!
4290 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004291 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004292 // The first two arguments (self and _cmd) are pointers; account for
4293 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004294 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004295 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004296 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004297 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004298 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004299 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004300 continue;
4301
Ken Dyck40775002010-01-11 17:06:35 +00004302 assert (sz.isPositive() &&
4303 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004304 ParmOffset += sz;
4305 }
Ken Dyck40775002010-01-11 17:06:35 +00004306 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004307 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004308 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004309
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004310 // Argument types.
4311 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004312 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004313 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004314 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004315 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004316 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004317 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4318 // Use array's original type only if it has known number of
4319 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004320 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004321 PType = PVDecl->getType();
4322 } else if (PType->isFunctionType())
4323 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004324 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4325 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004326 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004327 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004328 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004329
4330 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004331}
4332
Daniel Dunbar4932b362008-08-28 04:38:10 +00004333/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004334/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004335/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4336/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004337/// Property attributes are stored as a comma-delimited C string. The simple
4338/// attributes readonly and bycopy are encoded as single characters. The
4339/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4340/// encoded as single characters, followed by an identifier. Property types
4341/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004342/// these attributes are defined by the following enumeration:
4343/// @code
4344/// enum PropertyAttributes {
4345/// kPropertyReadOnly = 'R', // property is read-only.
4346/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4347/// kPropertyByref = '&', // property is a reference to the value last assigned
4348/// kPropertyDynamic = 'D', // property is dynamic
4349/// kPropertyGetter = 'G', // followed by getter selector name
4350/// kPropertySetter = 'S', // followed by setter selector name
4351/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004352/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004353/// kPropertyWeak = 'W' // 'weak' property
4354/// kPropertyStrong = 'P' // property GC'able
4355/// kPropertyNonAtomic = 'N' // property non-atomic
4356/// };
4357/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004358void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004359 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004360 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004361 // Collect information from the property implementation decl(s).
4362 bool Dynamic = false;
4363 ObjCPropertyImplDecl *SynthesizePID = 0;
4364
4365 // FIXME: Duplicated code due to poor abstraction.
4366 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004367 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004368 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4369 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004370 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004371 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004372 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004373 if (PID->getPropertyDecl() == PD) {
4374 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4375 Dynamic = true;
4376 } else {
4377 SynthesizePID = PID;
4378 }
4379 }
4380 }
4381 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004382 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004383 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004384 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004385 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004386 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004387 if (PID->getPropertyDecl() == PD) {
4388 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4389 Dynamic = true;
4390 } else {
4391 SynthesizePID = PID;
4392 }
4393 }
Mike Stump11289f42009-09-09 15:08:12 +00004394 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004395 }
4396 }
4397
4398 // FIXME: This is not very efficient.
4399 S = "T";
4400
4401 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004402 // GCC has some special rules regarding encoding of properties which
4403 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004404 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004405 true /* outermost type */,
4406 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004407
4408 if (PD->isReadOnly()) {
4409 S += ",R";
4410 } else {
4411 switch (PD->getSetterKind()) {
4412 case ObjCPropertyDecl::Assign: break;
4413 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004414 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004415 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004416 }
4417 }
4418
4419 // It really isn't clear at all what this means, since properties
4420 // are "dynamic by default".
4421 if (Dynamic)
4422 S += ",D";
4423
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004424 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4425 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004426
Daniel Dunbar4932b362008-08-28 04:38:10 +00004427 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4428 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004429 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004430 }
4431
4432 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4433 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004434 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004435 }
4436
4437 if (SynthesizePID) {
4438 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4439 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004440 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004441 }
4442
4443 // FIXME: OBJCGC: weak & strong
4444}
4445
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004446/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004447/// Another legacy compatibility encoding: 32-bit longs are encoded as
4448/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004449/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4450///
4451void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004452 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004453 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004454 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004455 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004456 else
Jay Foad39c79802011-01-12 09:06:06 +00004457 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004458 PointeeTy = IntTy;
4459 }
4460 }
4461}
4462
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004463void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004464 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004465 // We follow the behavior of gcc, expanding structures which are
4466 // directly pointed to, and expanding embedded structures. Note that
4467 // these rules are sufficient to prevent recursive encoding of the
4468 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004469 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004470 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004471}
4472
David Chisnallb190a2c2010-06-04 01:10:52 +00004473static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4474 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004475 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004476 case BuiltinType::Void: return 'v';
4477 case BuiltinType::Bool: return 'B';
4478 case BuiltinType::Char_U:
4479 case BuiltinType::UChar: return 'C';
4480 case BuiltinType::UShort: return 'S';
4481 case BuiltinType::UInt: return 'I';
4482 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004483 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004484 case BuiltinType::UInt128: return 'T';
4485 case BuiltinType::ULongLong: return 'Q';
4486 case BuiltinType::Char_S:
4487 case BuiltinType::SChar: return 'c';
4488 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004489 case BuiltinType::WChar_S:
4490 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004491 case BuiltinType::Int: return 'i';
4492 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004493 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004494 case BuiltinType::LongLong: return 'q';
4495 case BuiltinType::Int128: return 't';
4496 case BuiltinType::Float: return 'f';
4497 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004498 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004499 }
4500}
4501
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004502static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4503 EnumDecl *Enum = ET->getDecl();
4504
4505 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4506 if (!Enum->isFixed())
4507 return 'i';
4508
4509 // The encoding of a fixed enum type matches its fixed underlying type.
4510 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4511}
4512
Jay Foad39c79802011-01-12 09:06:06 +00004513static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004514 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004515 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004516 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004517 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4518 // The GNU runtime requires more information; bitfields are encoded as b,
4519 // then the offset (in bits) of the first element, then the type of the
4520 // bitfield, then the size in bits. For example, in this structure:
4521 //
4522 // struct
4523 // {
4524 // int integer;
4525 // int flags:2;
4526 // };
4527 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4528 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4529 // information is not especially sensible, but we're stuck with it for
4530 // compatibility with GCC, although providing it breaks anything that
4531 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004532 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004533 const RecordDecl *RD = FD->getParent();
4534 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004535 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004536 if (const EnumType *ET = T->getAs<EnumType>())
4537 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004538 else
Jay Foad39c79802011-01-12 09:06:06 +00004539 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004540 }
Richard Smithcaf33902011-10-10 18:28:20 +00004541 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004542}
4543
Daniel Dunbar07d07852009-10-18 21:17:35 +00004544// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004545void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4546 bool ExpandPointedToStructures,
4547 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004548 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004549 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004550 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004551 bool StructField,
4552 bool EncodeBlockParameters,
4553 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004554 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004555 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004556 return EncodeBitField(this, S, T, FD);
4557 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004558 return;
4559 }
Mike Stump11289f42009-09-09 15:08:12 +00004560
John McCall9dd450b2009-09-21 23:43:11 +00004561 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004562 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004563 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004564 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004565 return;
4566 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004567
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004568 // encoding for pointer or r3eference types.
4569 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004570 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004571 if (PT->isObjCSelType()) {
4572 S += ':';
4573 return;
4574 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004575 PointeeTy = PT->getPointeeType();
4576 }
4577 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4578 PointeeTy = RT->getPointeeType();
4579 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004580 bool isReadOnly = false;
4581 // For historical/compatibility reasons, the read-only qualifier of the
4582 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4583 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004584 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004585 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004586 if (OutermostType && T.isConstQualified()) {
4587 isReadOnly = true;
4588 S += 'r';
4589 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004590 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004591 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004592 while (P->getAs<PointerType>())
4593 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004594 if (P.isConstQualified()) {
4595 isReadOnly = true;
4596 S += 'r';
4597 }
4598 }
4599 if (isReadOnly) {
4600 // Another legacy compatibility encoding. Some ObjC qualifier and type
4601 // combinations need to be rearranged.
4602 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004603 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004604 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004605 }
Mike Stump11289f42009-09-09 15:08:12 +00004606
Anders Carlssond8499822007-10-29 05:01:08 +00004607 if (PointeeTy->isCharType()) {
4608 // char pointer types should be encoded as '*' unless it is a
4609 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004610 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004611 S += '*';
4612 return;
4613 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004614 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004615 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4616 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4617 S += '#';
4618 return;
4619 }
4620 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4621 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4622 S += '@';
4623 return;
4624 }
4625 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004626 }
Anders Carlssond8499822007-10-29 05:01:08 +00004627 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004628 getLegacyIntegralTypeEncoding(PointeeTy);
4629
Mike Stump11289f42009-09-09 15:08:12 +00004630 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004631 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004632 return;
4633 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004634
Chris Lattnere7cabb92009-07-13 00:10:46 +00004635 if (const ArrayType *AT =
4636 // Ignore type qualifiers etc.
4637 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004638 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004639 // Incomplete arrays are encoded as a pointer to the array element.
4640 S += '^';
4641
Mike Stump11289f42009-09-09 15:08:12 +00004642 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004643 false, ExpandStructures, FD);
4644 } else {
4645 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004646
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004647 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4648 if (getTypeSize(CAT->getElementType()) == 0)
4649 S += '0';
4650 else
4651 S += llvm::utostr(CAT->getSize().getZExtValue());
4652 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004653 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004654 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4655 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004656 S += '0';
4657 }
Mike Stump11289f42009-09-09 15:08:12 +00004658
4659 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004660 false, ExpandStructures, FD);
4661 S += ']';
4662 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004663 return;
4664 }
Mike Stump11289f42009-09-09 15:08:12 +00004665
John McCall9dd450b2009-09-21 23:43:11 +00004666 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004667 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004668 return;
4669 }
Mike Stump11289f42009-09-09 15:08:12 +00004670
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004671 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004672 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004673 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004674 // Anonymous structures print as '?'
4675 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4676 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004677 if (ClassTemplateSpecializationDecl *Spec
4678 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4679 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4680 std::string TemplateArgsStr
4681 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004682 TemplateArgs.data(),
4683 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004684 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004685
4686 S += TemplateArgsStr;
4687 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004688 } else {
4689 S += '?';
4690 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004691 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004692 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004693 if (!RDecl->isUnion()) {
4694 getObjCEncodingForStructureImpl(RDecl, S, FD);
4695 } else {
4696 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4697 FieldEnd = RDecl->field_end();
4698 Field != FieldEnd; ++Field) {
4699 if (FD) {
4700 S += '"';
4701 S += Field->getNameAsString();
4702 S += '"';
4703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004705 // Special case bit-fields.
4706 if (Field->isBitField()) {
4707 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004708 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004709 } else {
4710 QualType qt = Field->getType();
4711 getLegacyIntegralTypeEncoding(qt);
4712 getObjCEncodingForTypeImpl(qt, S, false, true,
4713 FD, /*OutermostType*/false,
4714 /*EncodingProperty*/false,
4715 /*StructField*/true);
4716 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004717 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004718 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004719 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004720 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004721 return;
4722 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004723
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004724 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004725 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004726 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004727 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004728 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004729 return;
4730 }
Mike Stump11289f42009-09-09 15:08:12 +00004731
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004732 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004733 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004734 if (EncodeBlockParameters) {
4735 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4736
4737 S += '<';
4738 // Block return type
4739 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4740 ExpandPointedToStructures, ExpandStructures,
4741 FD,
4742 false /* OutermostType */,
4743 EncodingProperty,
4744 false /* StructField */,
4745 EncodeBlockParameters,
4746 EncodeClassNames);
4747 // Block self
4748 S += "@?";
4749 // Block parameters
4750 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4751 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4752 E = FPT->arg_type_end(); I && (I != E); ++I) {
4753 getObjCEncodingForTypeImpl(*I, S,
4754 ExpandPointedToStructures,
4755 ExpandStructures,
4756 FD,
4757 false /* OutermostType */,
4758 EncodingProperty,
4759 false /* StructField */,
4760 EncodeBlockParameters,
4761 EncodeClassNames);
4762 }
4763 }
4764 S += '>';
4765 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004766 return;
4767 }
Mike Stump11289f42009-09-09 15:08:12 +00004768
John McCall8b07ec22010-05-15 11:32:37 +00004769 // Ignore protocol qualifiers when mangling at this level.
4770 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4771 T = OT->getBaseType();
4772
John McCall8ccfcb52009-09-24 19:53:00 +00004773 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004774 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004775 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004776 S += '{';
4777 const IdentifierInfo *II = OI->getIdentifier();
4778 S += II->getName();
4779 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004780 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004781 DeepCollectObjCIvars(OI, true, Ivars);
4782 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004783 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004784 if (Field->isBitField())
4785 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004786 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004787 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004788 }
4789 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004790 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004791 }
Mike Stump11289f42009-09-09 15:08:12 +00004792
John McCall9dd450b2009-09-21 23:43:11 +00004793 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004794 if (OPT->isObjCIdType()) {
4795 S += '@';
4796 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004797 }
Mike Stump11289f42009-09-09 15:08:12 +00004798
Steve Narofff0c86112009-10-28 22:03:49 +00004799 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4800 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4801 // Since this is a binary compatibility issue, need to consult with runtime
4802 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004803 S += '#';
4804 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004805 }
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattnere7cabb92009-07-13 00:10:46 +00004807 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004808 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004809 ExpandPointedToStructures,
4810 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004811 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004812 // Note that we do extended encoding of protocol qualifer list
4813 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004814 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004815 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4816 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004817 S += '<';
4818 S += (*I)->getNameAsString();
4819 S += '>';
4820 }
4821 S += '"';
4822 }
4823 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004824 }
Mike Stump11289f42009-09-09 15:08:12 +00004825
Chris Lattnere7cabb92009-07-13 00:10:46 +00004826 QualType PointeeTy = OPT->getPointeeType();
4827 if (!EncodingProperty &&
4828 isa<TypedefType>(PointeeTy.getTypePtr())) {
4829 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004830 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004831 // {...};
4832 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004833 getObjCEncodingForTypeImpl(PointeeTy, S,
4834 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004835 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004836 return;
4837 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004838
4839 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004840 if (OPT->getInterfaceDecl() &&
4841 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004842 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004843 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004844 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4845 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004846 S += '<';
4847 S += (*I)->getNameAsString();
4848 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004849 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004850 S += '"';
4851 }
4852 return;
4853 }
Mike Stump11289f42009-09-09 15:08:12 +00004854
John McCalla9e6e8d2010-05-17 23:56:34 +00004855 // gcc just blithely ignores member pointers.
4856 // TODO: maybe there should be a mangling for these
4857 if (T->getAs<MemberPointerType>())
4858 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004859
4860 if (T->isVectorType()) {
4861 // This matches gcc's encoding, even though technically it is
4862 // insufficient.
4863 // FIXME. We should do a better job than gcc.
4864 return;
4865 }
4866
David Blaikie83d382b2011-09-23 05:06:16 +00004867 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004868}
4869
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004870void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4871 std::string &S,
4872 const FieldDecl *FD,
4873 bool includeVBases) const {
4874 assert(RDecl && "Expected non-null RecordDecl");
4875 assert(!RDecl->isUnion() && "Should not be called for unions");
4876 if (!RDecl->getDefinition())
4877 return;
4878
4879 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4880 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4881 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4882
4883 if (CXXRec) {
4884 for (CXXRecordDecl::base_class_iterator
4885 BI = CXXRec->bases_begin(),
4886 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4887 if (!BI->isVirtual()) {
4888 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004889 if (base->isEmpty())
4890 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004891 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004892 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4893 std::make_pair(offs, base));
4894 }
4895 }
4896 }
4897
4898 unsigned i = 0;
4899 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4900 FieldEnd = RDecl->field_end();
4901 Field != FieldEnd; ++Field, ++i) {
4902 uint64_t offs = layout.getFieldOffset(i);
4903 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004904 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004905 }
4906
4907 if (CXXRec && includeVBases) {
4908 for (CXXRecordDecl::base_class_iterator
4909 BI = CXXRec->vbases_begin(),
4910 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4911 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004912 if (base->isEmpty())
4913 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004914 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004915 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4916 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4917 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004918 }
4919 }
4920
4921 CharUnits size;
4922 if (CXXRec) {
4923 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4924 } else {
4925 size = layout.getSize();
4926 }
4927
4928 uint64_t CurOffs = 0;
4929 std::multimap<uint64_t, NamedDecl *>::iterator
4930 CurLayObj = FieldOrBaseOffsets.begin();
4931
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004932 if (CXXRec && CXXRec->isDynamicClass() &&
4933 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004934 if (FD) {
4935 S += "\"_vptr$";
4936 std::string recname = CXXRec->getNameAsString();
4937 if (recname.empty()) recname = "?";
4938 S += recname;
4939 S += '"';
4940 }
4941 S += "^^?";
4942 CurOffs += getTypeSize(VoidPtrTy);
4943 }
4944
4945 if (!RDecl->hasFlexibleArrayMember()) {
4946 // Mark the end of the structure.
4947 uint64_t offs = toBits(size);
4948 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4949 std::make_pair(offs, (NamedDecl*)0));
4950 }
4951
4952 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4953 assert(CurOffs <= CurLayObj->first);
4954
4955 if (CurOffs < CurLayObj->first) {
4956 uint64_t padding = CurLayObj->first - CurOffs;
4957 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4958 // packing/alignment of members is different that normal, in which case
4959 // the encoding will be out-of-sync with the real layout.
4960 // If the runtime switches to just consider the size of types without
4961 // taking into account alignment, we could make padding explicit in the
4962 // encoding (e.g. using arrays of chars). The encoding strings would be
4963 // longer then though.
4964 CurOffs += padding;
4965 }
4966
4967 NamedDecl *dcl = CurLayObj->second;
4968 if (dcl == 0)
4969 break; // reached end of structure.
4970
4971 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4972 // We expand the bases without their virtual bases since those are going
4973 // in the initial structure. Note that this differs from gcc which
4974 // expands virtual bases each time one is encountered in the hierarchy,
4975 // making the encoding type bigger than it really is.
4976 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004977 assert(!base->isEmpty());
4978 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004979 } else {
4980 FieldDecl *field = cast<FieldDecl>(dcl);
4981 if (FD) {
4982 S += '"';
4983 S += field->getNameAsString();
4984 S += '"';
4985 }
4986
4987 if (field->isBitField()) {
4988 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004989 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004990 } else {
4991 QualType qt = field->getType();
4992 getLegacyIntegralTypeEncoding(qt);
4993 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4994 /*OutermostType*/false,
4995 /*EncodingProperty*/false,
4996 /*StructField*/true);
4997 CurOffs += getTypeSize(field->getType());
4998 }
4999 }
5000 }
5001}
5002
Mike Stump11289f42009-09-09 15:08:12 +00005003void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005004 std::string& S) const {
5005 if (QT & Decl::OBJC_TQ_In)
5006 S += 'n';
5007 if (QT & Decl::OBJC_TQ_Inout)
5008 S += 'N';
5009 if (QT & Decl::OBJC_TQ_Out)
5010 S += 'o';
5011 if (QT & Decl::OBJC_TQ_Bycopy)
5012 S += 'O';
5013 if (QT & Decl::OBJC_TQ_Byref)
5014 S += 'R';
5015 if (QT & Decl::OBJC_TQ_Oneway)
5016 S += 'V';
5017}
5018
Douglas Gregor3ea72692011-08-12 05:46:01 +00005019TypedefDecl *ASTContext::getObjCIdDecl() const {
5020 if (!ObjCIdDecl) {
5021 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5022 T = getObjCObjectPointerType(T);
5023 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5024 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5025 getTranslationUnitDecl(),
5026 SourceLocation(), SourceLocation(),
5027 &Idents.get("id"), IdInfo);
5028 }
5029
5030 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005031}
5032
Douglas Gregor52e02802011-08-12 06:17:30 +00005033TypedefDecl *ASTContext::getObjCSelDecl() const {
5034 if (!ObjCSelDecl) {
5035 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5036 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5037 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5038 getTranslationUnitDecl(),
5039 SourceLocation(), SourceLocation(),
5040 &Idents.get("SEL"), SelInfo);
5041 }
5042 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005043}
5044
Douglas Gregor0a586182011-08-12 05:59:41 +00005045TypedefDecl *ASTContext::getObjCClassDecl() const {
5046 if (!ObjCClassDecl) {
5047 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5048 T = getObjCObjectPointerType(T);
5049 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5050 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5051 getTranslationUnitDecl(),
5052 SourceLocation(), SourceLocation(),
5053 &Idents.get("Class"), ClassInfo);
5054 }
5055
5056 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005057}
5058
Douglas Gregord53ae832012-01-17 18:09:05 +00005059ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5060 if (!ObjCProtocolClassDecl) {
5061 ObjCProtocolClassDecl
5062 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5063 SourceLocation(),
5064 &Idents.get("Protocol"),
5065 /*PrevDecl=*/0,
5066 SourceLocation(), true);
5067 }
5068
5069 return ObjCProtocolClassDecl;
5070}
5071
Meador Inge5d3fb222012-06-16 03:34:49 +00005072//===----------------------------------------------------------------------===//
5073// __builtin_va_list Construction Functions
5074//===----------------------------------------------------------------------===//
5075
5076static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5077 // typedef char* __builtin_va_list;
5078 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5079 TypeSourceInfo *TInfo
5080 = Context->getTrivialTypeSourceInfo(CharPtrType);
5081
5082 TypedefDecl *VaListTypeDecl
5083 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5084 Context->getTranslationUnitDecl(),
5085 SourceLocation(), SourceLocation(),
5086 &Context->Idents.get("__builtin_va_list"),
5087 TInfo);
5088 return VaListTypeDecl;
5089}
5090
5091static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5092 // typedef void* __builtin_va_list;
5093 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5094 TypeSourceInfo *TInfo
5095 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5096
5097 TypedefDecl *VaListTypeDecl
5098 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5099 Context->getTranslationUnitDecl(),
5100 SourceLocation(), SourceLocation(),
5101 &Context->Idents.get("__builtin_va_list"),
5102 TInfo);
5103 return VaListTypeDecl;
5104}
5105
5106static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5107 // typedef struct __va_list_tag {
5108 RecordDecl *VaListTagDecl;
5109
5110 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5111 Context->getTranslationUnitDecl(),
5112 &Context->Idents.get("__va_list_tag"));
5113 VaListTagDecl->startDefinition();
5114
5115 const size_t NumFields = 5;
5116 QualType FieldTypes[NumFields];
5117 const char *FieldNames[NumFields];
5118
5119 // unsigned char gpr;
5120 FieldTypes[0] = Context->UnsignedCharTy;
5121 FieldNames[0] = "gpr";
5122
5123 // unsigned char fpr;
5124 FieldTypes[1] = Context->UnsignedCharTy;
5125 FieldNames[1] = "fpr";
5126
5127 // unsigned short reserved;
5128 FieldTypes[2] = Context->UnsignedShortTy;
5129 FieldNames[2] = "reserved";
5130
5131 // void* overflow_arg_area;
5132 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5133 FieldNames[3] = "overflow_arg_area";
5134
5135 // void* reg_save_area;
5136 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5137 FieldNames[4] = "reg_save_area";
5138
5139 // Create fields
5140 for (unsigned i = 0; i < NumFields; ++i) {
5141 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5142 SourceLocation(),
5143 SourceLocation(),
5144 &Context->Idents.get(FieldNames[i]),
5145 FieldTypes[i], /*TInfo=*/0,
5146 /*BitWidth=*/0,
5147 /*Mutable=*/false,
5148 ICIS_NoInit);
5149 Field->setAccess(AS_public);
5150 VaListTagDecl->addDecl(Field);
5151 }
5152 VaListTagDecl->completeDefinition();
5153 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005154 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005155
5156 // } __va_list_tag;
5157 TypedefDecl *VaListTagTypedefDecl
5158 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5159 Context->getTranslationUnitDecl(),
5160 SourceLocation(), SourceLocation(),
5161 &Context->Idents.get("__va_list_tag"),
5162 Context->getTrivialTypeSourceInfo(VaListTagType));
5163 QualType VaListTagTypedefType =
5164 Context->getTypedefType(VaListTagTypedefDecl);
5165
5166 // typedef __va_list_tag __builtin_va_list[1];
5167 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5168 QualType VaListTagArrayType
5169 = Context->getConstantArrayType(VaListTagTypedefType,
5170 Size, ArrayType::Normal, 0);
5171 TypeSourceInfo *TInfo
5172 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5173 TypedefDecl *VaListTypedefDecl
5174 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5175 Context->getTranslationUnitDecl(),
5176 SourceLocation(), SourceLocation(),
5177 &Context->Idents.get("__builtin_va_list"),
5178 TInfo);
5179
5180 return VaListTypedefDecl;
5181}
5182
5183static TypedefDecl *
5184CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5185 // typedef struct __va_list_tag {
5186 RecordDecl *VaListTagDecl;
5187 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5188 Context->getTranslationUnitDecl(),
5189 &Context->Idents.get("__va_list_tag"));
5190 VaListTagDecl->startDefinition();
5191
5192 const size_t NumFields = 4;
5193 QualType FieldTypes[NumFields];
5194 const char *FieldNames[NumFields];
5195
5196 // unsigned gp_offset;
5197 FieldTypes[0] = Context->UnsignedIntTy;
5198 FieldNames[0] = "gp_offset";
5199
5200 // unsigned fp_offset;
5201 FieldTypes[1] = Context->UnsignedIntTy;
5202 FieldNames[1] = "fp_offset";
5203
5204 // void* overflow_arg_area;
5205 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5206 FieldNames[2] = "overflow_arg_area";
5207
5208 // void* reg_save_area;
5209 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5210 FieldNames[3] = "reg_save_area";
5211
5212 // Create fields
5213 for (unsigned i = 0; i < NumFields; ++i) {
5214 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5215 VaListTagDecl,
5216 SourceLocation(),
5217 SourceLocation(),
5218 &Context->Idents.get(FieldNames[i]),
5219 FieldTypes[i], /*TInfo=*/0,
5220 /*BitWidth=*/0,
5221 /*Mutable=*/false,
5222 ICIS_NoInit);
5223 Field->setAccess(AS_public);
5224 VaListTagDecl->addDecl(Field);
5225 }
5226 VaListTagDecl->completeDefinition();
5227 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005228 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005229
5230 // } __va_list_tag;
5231 TypedefDecl *VaListTagTypedefDecl
5232 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5233 Context->getTranslationUnitDecl(),
5234 SourceLocation(), SourceLocation(),
5235 &Context->Idents.get("__va_list_tag"),
5236 Context->getTrivialTypeSourceInfo(VaListTagType));
5237 QualType VaListTagTypedefType =
5238 Context->getTypedefType(VaListTagTypedefDecl);
5239
5240 // typedef __va_list_tag __builtin_va_list[1];
5241 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5242 QualType VaListTagArrayType
5243 = Context->getConstantArrayType(VaListTagTypedefType,
5244 Size, ArrayType::Normal,0);
5245 TypeSourceInfo *TInfo
5246 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5247 TypedefDecl *VaListTypedefDecl
5248 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5249 Context->getTranslationUnitDecl(),
5250 SourceLocation(), SourceLocation(),
5251 &Context->Idents.get("__builtin_va_list"),
5252 TInfo);
5253
5254 return VaListTypedefDecl;
5255}
5256
5257static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5258 // typedef int __builtin_va_list[4];
5259 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5260 QualType IntArrayType
5261 = Context->getConstantArrayType(Context->IntTy,
5262 Size, ArrayType::Normal, 0);
5263 TypedefDecl *VaListTypedefDecl
5264 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5265 Context->getTranslationUnitDecl(),
5266 SourceLocation(), SourceLocation(),
5267 &Context->Idents.get("__builtin_va_list"),
5268 Context->getTrivialTypeSourceInfo(IntArrayType));
5269
5270 return VaListTypedefDecl;
5271}
5272
5273static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5274 TargetInfo::BuiltinVaListKind Kind) {
5275 switch (Kind) {
5276 case TargetInfo::CharPtrBuiltinVaList:
5277 return CreateCharPtrBuiltinVaListDecl(Context);
5278 case TargetInfo::VoidPtrBuiltinVaList:
5279 return CreateVoidPtrBuiltinVaListDecl(Context);
5280 case TargetInfo::PowerABIBuiltinVaList:
5281 return CreatePowerABIBuiltinVaListDecl(Context);
5282 case TargetInfo::X86_64ABIBuiltinVaList:
5283 return CreateX86_64ABIBuiltinVaListDecl(Context);
5284 case TargetInfo::PNaClABIBuiltinVaList:
5285 return CreatePNaClABIBuiltinVaListDecl(Context);
5286 }
5287
5288 llvm_unreachable("Unhandled __builtin_va_list type kind");
5289}
5290
5291TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5292 if (!BuiltinVaListDecl)
5293 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5294
5295 return BuiltinVaListDecl;
5296}
5297
Meador Ingecfb60902012-07-01 15:57:25 +00005298QualType ASTContext::getVaListTagType() const {
5299 // Force the creation of VaListTagTy by building the __builtin_va_list
5300 // declaration.
5301 if (VaListTagTy.isNull())
5302 (void) getBuiltinVaListDecl();
5303
5304 return VaListTagTy;
5305}
5306
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005307void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005308 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005309 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005310
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005311 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005312}
5313
John McCalld28ae272009-12-02 08:04:21 +00005314/// \brief Retrieve the template name that corresponds to a non-empty
5315/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005316TemplateName
5317ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5318 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005319 unsigned size = End - Begin;
5320 assert(size > 1 && "set is not overloaded!");
5321
5322 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5323 size * sizeof(FunctionTemplateDecl*));
5324 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5325
5326 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005327 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005328 NamedDecl *D = *I;
5329 assert(isa<FunctionTemplateDecl>(D) ||
5330 (isa<UsingShadowDecl>(D) &&
5331 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5332 *Storage++ = D;
5333 }
5334
5335 return TemplateName(OT);
5336}
5337
Douglas Gregordc572a32009-03-30 22:58:21 +00005338/// \brief Retrieve the template name that represents a qualified
5339/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005340TemplateName
5341ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5342 bool TemplateKeyword,
5343 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005344 assert(NNS && "Missing nested-name-specifier in qualified template name");
5345
Douglas Gregorc42075a2010-02-04 18:10:26 +00005346 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005347 llvm::FoldingSetNodeID ID;
5348 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5349
5350 void *InsertPos = 0;
5351 QualifiedTemplateName *QTN =
5352 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5353 if (!QTN) {
5354 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5355 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5356 }
5357
5358 return TemplateName(QTN);
5359}
5360
5361/// \brief Retrieve the template name that represents a dependent
5362/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005363TemplateName
5364ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5365 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005366 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005367 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005368
5369 llvm::FoldingSetNodeID ID;
5370 DependentTemplateName::Profile(ID, NNS, Name);
5371
5372 void *InsertPos = 0;
5373 DependentTemplateName *QTN =
5374 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5375
5376 if (QTN)
5377 return TemplateName(QTN);
5378
5379 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5380 if (CanonNNS == NNS) {
5381 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5382 } else {
5383 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5384 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005385 DependentTemplateName *CheckQTN =
5386 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5387 assert(!CheckQTN && "Dependent type name canonicalization broken");
5388 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005389 }
5390
5391 DependentTemplateNames.InsertNode(QTN, InsertPos);
5392 return TemplateName(QTN);
5393}
5394
Douglas Gregor71395fa2009-11-04 00:56:37 +00005395/// \brief Retrieve the template name that represents a dependent
5396/// template name such as \c MetaFun::template operator+.
5397TemplateName
5398ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005399 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005400 assert((!NNS || NNS->isDependent()) &&
5401 "Nested name specifier must be dependent");
5402
5403 llvm::FoldingSetNodeID ID;
5404 DependentTemplateName::Profile(ID, NNS, Operator);
5405
5406 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005407 DependentTemplateName *QTN
5408 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005409
5410 if (QTN)
5411 return TemplateName(QTN);
5412
5413 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5414 if (CanonNNS == NNS) {
5415 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5416 } else {
5417 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5418 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005419
5420 DependentTemplateName *CheckQTN
5421 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5422 assert(!CheckQTN && "Dependent template name canonicalization broken");
5423 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005424 }
5425
5426 DependentTemplateNames.InsertNode(QTN, InsertPos);
5427 return TemplateName(QTN);
5428}
5429
Douglas Gregor5590be02011-01-15 06:45:20 +00005430TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005431ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5432 TemplateName replacement) const {
5433 llvm::FoldingSetNodeID ID;
5434 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5435
5436 void *insertPos = 0;
5437 SubstTemplateTemplateParmStorage *subst
5438 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5439
5440 if (!subst) {
5441 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5442 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5443 }
5444
5445 return TemplateName(subst);
5446}
5447
5448TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005449ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5450 const TemplateArgument &ArgPack) const {
5451 ASTContext &Self = const_cast<ASTContext &>(*this);
5452 llvm::FoldingSetNodeID ID;
5453 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5454
5455 void *InsertPos = 0;
5456 SubstTemplateTemplateParmPackStorage *Subst
5457 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5458
5459 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005460 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005461 ArgPack.pack_size(),
5462 ArgPack.pack_begin());
5463 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5464 }
5465
5466 return TemplateName(Subst);
5467}
5468
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005469/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005470/// TargetInfo, produce the corresponding type. The unsigned @p Type
5471/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005472CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005473 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005474 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005475 case TargetInfo::SignedShort: return ShortTy;
5476 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5477 case TargetInfo::SignedInt: return IntTy;
5478 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5479 case TargetInfo::SignedLong: return LongTy;
5480 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5481 case TargetInfo::SignedLongLong: return LongLongTy;
5482 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5483 }
5484
David Blaikie83d382b2011-09-23 05:06:16 +00005485 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005486}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005487
5488//===----------------------------------------------------------------------===//
5489// Type Predicates.
5490//===----------------------------------------------------------------------===//
5491
Fariborz Jahanian96207692009-02-18 21:49:28 +00005492/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5493/// garbage collection attribute.
5494///
John McCall553d45a2011-01-12 00:34:59 +00005495Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005496 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005497 return Qualifiers::GCNone;
5498
David Blaikiebbafb8a2012-03-11 07:00:24 +00005499 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005500 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5501
5502 // Default behaviour under objective-C's gc is for ObjC pointers
5503 // (or pointers to them) be treated as though they were declared
5504 // as __strong.
5505 if (GCAttrs == Qualifiers::GCNone) {
5506 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5507 return Qualifiers::Strong;
5508 else if (Ty->isPointerType())
5509 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5510 } else {
5511 // It's not valid to set GC attributes on anything that isn't a
5512 // pointer.
5513#ifndef NDEBUG
5514 QualType CT = Ty->getCanonicalTypeInternal();
5515 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5516 CT = AT->getElementType();
5517 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5518#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005519 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005520 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005521}
5522
Chris Lattner49af6a42008-04-07 06:51:04 +00005523//===----------------------------------------------------------------------===//
5524// Type Compatibility Testing
5525//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005526
Mike Stump11289f42009-09-09 15:08:12 +00005527/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005528/// compatible.
5529static bool areCompatVectorTypes(const VectorType *LHS,
5530 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005531 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005532 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005533 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005534}
5535
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005536bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5537 QualType SecondVec) {
5538 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5539 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5540
5541 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5542 return true;
5543
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005544 // Treat Neon vector types and most AltiVec vector types as if they are the
5545 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005546 const VectorType *First = FirstVec->getAs<VectorType>();
5547 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005548 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005549 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005550 First->getVectorKind() != VectorType::AltiVecPixel &&
5551 First->getVectorKind() != VectorType::AltiVecBool &&
5552 Second->getVectorKind() != VectorType::AltiVecPixel &&
5553 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005554 return true;
5555
5556 return false;
5557}
5558
Steve Naroff8e6aee52009-07-23 01:01:38 +00005559//===----------------------------------------------------------------------===//
5560// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5561//===----------------------------------------------------------------------===//
5562
5563/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5564/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005565bool
5566ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5567 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005568 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005569 return true;
5570 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5571 E = rProto->protocol_end(); PI != E; ++PI)
5572 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5573 return true;
5574 return false;
5575}
5576
Steve Naroff8e6aee52009-07-23 01:01:38 +00005577/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5578/// return true if lhs's protocols conform to rhs's protocol; false
5579/// otherwise.
5580bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5581 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5582 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5583 return false;
5584}
5585
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005586/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5587/// Class<p1, ...>.
5588bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5589 QualType rhs) {
5590 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5591 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5592 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5593
5594 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5595 E = lhsQID->qual_end(); I != E; ++I) {
5596 bool match = false;
5597 ObjCProtocolDecl *lhsProto = *I;
5598 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5599 E = rhsOPT->qual_end(); J != E; ++J) {
5600 ObjCProtocolDecl *rhsProto = *J;
5601 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5602 match = true;
5603 break;
5604 }
5605 }
5606 if (!match)
5607 return false;
5608 }
5609 return true;
5610}
5611
Steve Naroff8e6aee52009-07-23 01:01:38 +00005612/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5613/// ObjCQualifiedIDType.
5614bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5615 bool compare) {
5616 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005617 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005618 lhs->isObjCIdType() || lhs->isObjCClassType())
5619 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005620 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005621 rhs->isObjCIdType() || rhs->isObjCClassType())
5622 return true;
5623
5624 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005625 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005626
Steve Naroff8e6aee52009-07-23 01:01:38 +00005627 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005628
Steve Naroff8e6aee52009-07-23 01:01:38 +00005629 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005630 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005631 // make sure we check the class hierarchy.
5632 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5633 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5634 E = lhsQID->qual_end(); I != E; ++I) {
5635 // when comparing an id<P> on lhs with a static type on rhs,
5636 // see if static class implements all of id's protocols, directly or
5637 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005638 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005639 return false;
5640 }
5641 }
5642 // If there are no qualifiers and no interface, we have an 'id'.
5643 return true;
5644 }
Mike Stump11289f42009-09-09 15:08:12 +00005645 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005646 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5647 E = lhsQID->qual_end(); I != E; ++I) {
5648 ObjCProtocolDecl *lhsProto = *I;
5649 bool match = false;
5650
5651 // when comparing an id<P> on lhs with a static type on rhs,
5652 // see if static class implements all of id's protocols, directly or
5653 // through its super class and categories.
5654 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5655 E = rhsOPT->qual_end(); J != E; ++J) {
5656 ObjCProtocolDecl *rhsProto = *J;
5657 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5658 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5659 match = true;
5660 break;
5661 }
5662 }
Mike Stump11289f42009-09-09 15:08:12 +00005663 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005664 // make sure we check the class hierarchy.
5665 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5666 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5667 E = lhsQID->qual_end(); I != E; ++I) {
5668 // when comparing an id<P> on lhs with a static type on rhs,
5669 // see if static class implements all of id's protocols, directly or
5670 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005671 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005672 match = true;
5673 break;
5674 }
5675 }
5676 }
5677 if (!match)
5678 return false;
5679 }
Mike Stump11289f42009-09-09 15:08:12 +00005680
Steve Naroff8e6aee52009-07-23 01:01:38 +00005681 return true;
5682 }
Mike Stump11289f42009-09-09 15:08:12 +00005683
Steve Naroff8e6aee52009-07-23 01:01:38 +00005684 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5685 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5686
Mike Stump11289f42009-09-09 15:08:12 +00005687 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005688 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005689 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005690 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5691 E = lhsOPT->qual_end(); I != E; ++I) {
5692 ObjCProtocolDecl *lhsProto = *I;
5693 bool match = false;
5694
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005695 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005696 // see if static class implements all of id's protocols, directly or
5697 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005698 // First, lhs protocols in the qualifier list must be found, direct
5699 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005700 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5701 E = rhsQID->qual_end(); J != E; ++J) {
5702 ObjCProtocolDecl *rhsProto = *J;
5703 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5704 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5705 match = true;
5706 break;
5707 }
5708 }
5709 if (!match)
5710 return false;
5711 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005712
5713 // Static class's protocols, or its super class or category protocols
5714 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5715 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5716 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5717 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5718 // This is rather dubious but matches gcc's behavior. If lhs has
5719 // no type qualifier and its class has no static protocol(s)
5720 // assume that it is mismatch.
5721 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5722 return false;
5723 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5724 LHSInheritedProtocols.begin(),
5725 E = LHSInheritedProtocols.end(); I != E; ++I) {
5726 bool match = false;
5727 ObjCProtocolDecl *lhsProto = (*I);
5728 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 }
5740 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005741 return true;
5742 }
5743 return false;
5744}
5745
Eli Friedman47f77112008-08-22 00:56:42 +00005746/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005747/// compatible for assignment from RHS to LHS. This handles validation of any
5748/// protocol qualifiers on the LHS or RHS.
5749///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005750bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5751 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005752 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5753 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5754
Steve Naroff1329fa02009-07-15 18:40:39 +00005755 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005756 if (LHS->isObjCUnqualifiedIdOrClass() ||
5757 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005758 return true;
5759
John McCall8b07ec22010-05-15 11:32:37 +00005760 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005761 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5762 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005763 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005764
5765 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5766 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5767 QualType(RHSOPT,0));
5768
John McCall8b07ec22010-05-15 11:32:37 +00005769 // If we have 2 user-defined types, fall into that path.
5770 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005771 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005772
Steve Naroff8e6aee52009-07-23 01:01:38 +00005773 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005774}
5775
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005776/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005777/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005778/// arguments in block literals. When passed as arguments, passing 'A*' where
5779/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5780/// not OK. For the return type, the opposite is not OK.
5781bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5782 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005783 const ObjCObjectPointerType *RHSOPT,
5784 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005785 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005786 return true;
5787
5788 if (LHSOPT->isObjCBuiltinType()) {
5789 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5790 }
5791
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005792 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005793 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5794 QualType(RHSOPT,0),
5795 false);
5796
5797 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5798 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5799 if (LHS && RHS) { // We have 2 user-defined types.
5800 if (LHS != RHS) {
5801 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005802 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005803 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005804 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005805 }
5806 else
5807 return true;
5808 }
5809 return false;
5810}
5811
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005812/// getIntersectionOfProtocols - This routine finds the intersection of set
5813/// of protocols inherited from two distinct objective-c pointer objects.
5814/// It is used to build composite qualifier list of the composite type of
5815/// the conditional expression involving two objective-c pointer objects.
5816static
5817void getIntersectionOfProtocols(ASTContext &Context,
5818 const ObjCObjectPointerType *LHSOPT,
5819 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005820 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005821
John McCall8b07ec22010-05-15 11:32:37 +00005822 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5823 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5824 assert(LHS->getInterface() && "LHS must have an interface base");
5825 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005826
5827 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5828 unsigned LHSNumProtocols = LHS->getNumProtocols();
5829 if (LHSNumProtocols > 0)
5830 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5831 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005832 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005833 Context.CollectInheritedProtocols(LHS->getInterface(),
5834 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005835 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5836 LHSInheritedProtocols.end());
5837 }
5838
5839 unsigned RHSNumProtocols = RHS->getNumProtocols();
5840 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005841 ObjCProtocolDecl **RHSProtocols =
5842 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005843 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5844 if (InheritedProtocolSet.count(RHSProtocols[i]))
5845 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005846 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005847 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005848 Context.CollectInheritedProtocols(RHS->getInterface(),
5849 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005850 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5851 RHSInheritedProtocols.begin(),
5852 E = RHSInheritedProtocols.end(); I != E; ++I)
5853 if (InheritedProtocolSet.count((*I)))
5854 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005855 }
5856}
5857
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005858/// areCommonBaseCompatible - Returns common base class of the two classes if
5859/// one found. Note that this is O'2 algorithm. But it will be called as the
5860/// last type comparison in a ?-exp of ObjC pointer types before a
5861/// warning is issued. So, its invokation is extremely rare.
5862QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005863 const ObjCObjectPointerType *Lptr,
5864 const ObjCObjectPointerType *Rptr) {
5865 const ObjCObjectType *LHS = Lptr->getObjectType();
5866 const ObjCObjectType *RHS = Rptr->getObjectType();
5867 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5868 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005869 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005870 return QualType();
5871
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005872 do {
John McCall8b07ec22010-05-15 11:32:37 +00005873 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005874 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005875 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005876 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5877
5878 QualType Result = QualType(LHS, 0);
5879 if (!Protocols.empty())
5880 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5881 Result = getObjCObjectPointerType(Result);
5882 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005883 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005884 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005885
5886 return QualType();
5887}
5888
John McCall8b07ec22010-05-15 11:32:37 +00005889bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5890 const ObjCObjectType *RHS) {
5891 assert(LHS->getInterface() && "LHS is not an interface type");
5892 assert(RHS->getInterface() && "RHS is not an interface type");
5893
Chris Lattner49af6a42008-04-07 06:51:04 +00005894 // Verify that the base decls are compatible: the RHS must be a subclass of
5895 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005896 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005897 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005898
Chris Lattner49af6a42008-04-07 06:51:04 +00005899 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5900 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005901 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005902 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005903
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005904 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5905 // more detailed analysis is required.
5906 if (RHS->getNumProtocols() == 0) {
5907 // OK, if LHS is a superclass of RHS *and*
5908 // this superclass is assignment compatible with LHS.
5909 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005910 bool IsSuperClass =
5911 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5912 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005913 // OK if conversion of LHS to SuperClass results in narrowing of types
5914 // ; i.e., SuperClass may implement at least one of the protocols
5915 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5916 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5917 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005918 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005919 // If super class has no protocols, it is not a match.
5920 if (SuperClassInheritedProtocols.empty())
5921 return false;
5922
5923 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5924 LHSPE = LHS->qual_end();
5925 LHSPI != LHSPE; LHSPI++) {
5926 bool SuperImplementsProtocol = false;
5927 ObjCProtocolDecl *LHSProto = (*LHSPI);
5928
5929 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5930 SuperClassInheritedProtocols.begin(),
5931 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5932 ObjCProtocolDecl *SuperClassProto = (*I);
5933 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5934 SuperImplementsProtocol = true;
5935 break;
5936 }
5937 }
5938 if (!SuperImplementsProtocol)
5939 return false;
5940 }
5941 return true;
5942 }
5943 return false;
5944 }
Mike Stump11289f42009-09-09 15:08:12 +00005945
John McCall8b07ec22010-05-15 11:32:37 +00005946 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5947 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005948 LHSPI != LHSPE; LHSPI++) {
5949 bool RHSImplementsProtocol = false;
5950
5951 // If the RHS doesn't implement the protocol on the left, the types
5952 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005953 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5954 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005955 RHSPI != RHSPE; RHSPI++) {
5956 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005957 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005958 break;
5959 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005960 }
5961 // FIXME: For better diagnostics, consider passing back the protocol name.
5962 if (!RHSImplementsProtocol)
5963 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005964 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005965 // The RHS implements all protocols listed on the LHS.
5966 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005967}
5968
Steve Naroffb7605152009-02-12 17:52:19 +00005969bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5970 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005971 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5972 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005973
Steve Naroff7cae42b2009-07-10 23:34:53 +00005974 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005975 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005976
5977 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5978 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005979}
5980
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005981bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5982 return canAssignObjCInterfaces(
5983 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5984 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5985}
5986
Mike Stump11289f42009-09-09 15:08:12 +00005987/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005988/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005989/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005990/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005991bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5992 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005993 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005994 return hasSameType(LHS, RHS);
5995
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005996 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005997}
5998
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005999bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006000 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006001}
6002
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006003bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6004 return !mergeTypes(LHS, RHS, true).isNull();
6005}
6006
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006007/// mergeTransparentUnionType - if T is a transparent union type and a member
6008/// of T is compatible with SubType, return the merged type, else return
6009/// QualType()
6010QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6011 bool OfBlockPointer,
6012 bool Unqualified) {
6013 if (const RecordType *UT = T->getAsUnionType()) {
6014 RecordDecl *UD = UT->getDecl();
6015 if (UD->hasAttr<TransparentUnionAttr>()) {
6016 for (RecordDecl::field_iterator it = UD->field_begin(),
6017 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006018 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006019 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6020 if (!MT.isNull())
6021 return MT;
6022 }
6023 }
6024 }
6025
6026 return QualType();
6027}
6028
6029/// mergeFunctionArgumentTypes - merge two types which appear as function
6030/// argument types
6031QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6032 bool OfBlockPointer,
6033 bool Unqualified) {
6034 // GNU extension: two types are compatible if they appear as a function
6035 // argument, one of the types is a transparent union type and the other
6036 // type is compatible with a union member
6037 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6038 Unqualified);
6039 if (!lmerge.isNull())
6040 return lmerge;
6041
6042 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6043 Unqualified);
6044 if (!rmerge.isNull())
6045 return rmerge;
6046
6047 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6048}
6049
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006050QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006051 bool OfBlockPointer,
6052 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006053 const FunctionType *lbase = lhs->getAs<FunctionType>();
6054 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006055 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6056 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006057 bool allLTypes = true;
6058 bool allRTypes = true;
6059
6060 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006061 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006062 if (OfBlockPointer) {
6063 QualType RHS = rbase->getResultType();
6064 QualType LHS = lbase->getResultType();
6065 bool UnqualifiedResult = Unqualified;
6066 if (!UnqualifiedResult)
6067 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006068 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006069 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006070 else
John McCall8c6b56f2010-12-15 01:06:38 +00006071 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6072 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006073 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006074
6075 if (Unqualified)
6076 retType = retType.getUnqualifiedType();
6077
6078 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6079 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6080 if (Unqualified) {
6081 LRetType = LRetType.getUnqualifiedType();
6082 RRetType = RRetType.getUnqualifiedType();
6083 }
6084
6085 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006086 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006087 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006088 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006089
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006090 // FIXME: double check this
6091 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6092 // rbase->getRegParmAttr() != 0 &&
6093 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006094 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6095 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006096
Douglas Gregor8c940862010-01-18 17:14:39 +00006097 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006098 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006099 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006100
John McCall8c6b56f2010-12-15 01:06:38 +00006101 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006102 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6103 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006104 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6105 return QualType();
6106
John McCall31168b02011-06-15 23:02:42 +00006107 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6108 return QualType();
6109
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006110 // functypes which return are preferred over those that do not.
6111 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6112 allLTypes = false;
6113 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6114 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006115 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6116 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006117
John McCall31168b02011-06-15 23:02:42 +00006118 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006119
Eli Friedman47f77112008-08-22 00:56:42 +00006120 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006121 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6122 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006123 unsigned lproto_nargs = lproto->getNumArgs();
6124 unsigned rproto_nargs = rproto->getNumArgs();
6125
6126 // Compatible functions must have the same number of arguments
6127 if (lproto_nargs != rproto_nargs)
6128 return QualType();
6129
6130 // Variadic and non-variadic functions aren't compatible
6131 if (lproto->isVariadic() != rproto->isVariadic())
6132 return QualType();
6133
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006134 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6135 return QualType();
6136
Fariborz Jahanian97676972011-09-28 21:52:05 +00006137 if (LangOpts.ObjCAutoRefCount &&
6138 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6139 return QualType();
6140
Eli Friedman47f77112008-08-22 00:56:42 +00006141 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006142 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006143 for (unsigned i = 0; i < lproto_nargs; i++) {
6144 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6145 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006146 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6147 OfBlockPointer,
6148 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006149 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006150
6151 if (Unqualified)
6152 argtype = argtype.getUnqualifiedType();
6153
Eli Friedman47f77112008-08-22 00:56:42 +00006154 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006155 if (Unqualified) {
6156 largtype = largtype.getUnqualifiedType();
6157 rargtype = rargtype.getUnqualifiedType();
6158 }
6159
Chris Lattner465fa322008-10-05 17:34:18 +00006160 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6161 allLTypes = false;
6162 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6163 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006164 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006165
Eli Friedman47f77112008-08-22 00:56:42 +00006166 if (allLTypes) return lhs;
6167 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006168
6169 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6170 EPI.ExtInfo = einfo;
6171 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006172 }
6173
6174 if (lproto) allRTypes = false;
6175 if (rproto) allLTypes = false;
6176
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006177 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006178 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006179 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006180 if (proto->isVariadic()) return QualType();
6181 // Check that the types are compatible with the types that
6182 // would result from default argument promotions (C99 6.7.5.3p15).
6183 // The only types actually affected are promotable integer
6184 // types and floats, which would be passed as a different
6185 // type depending on whether the prototype is visible.
6186 unsigned proto_nargs = proto->getNumArgs();
6187 for (unsigned i = 0; i < proto_nargs; ++i) {
6188 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006189
6190 // Look at the promotion type of enum types, since that is the type used
6191 // to pass enum values.
6192 if (const EnumType *Enum = argTy->getAs<EnumType>())
6193 argTy = Enum->getDecl()->getPromotionType();
6194
Eli Friedman47f77112008-08-22 00:56:42 +00006195 if (argTy->isPromotableIntegerType() ||
6196 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6197 return QualType();
6198 }
6199
6200 if (allLTypes) return lhs;
6201 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006202
6203 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6204 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006205 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006206 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006207 }
6208
6209 if (allLTypes) return lhs;
6210 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006211 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006212}
6213
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006214QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006215 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006216 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006217 // C++ [expr]: If an expression initially has the type "reference to T", the
6218 // type is adjusted to "T" prior to any further analysis, the expression
6219 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006220 // expression is an lvalue unless the reference is an rvalue reference and
6221 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006222 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6223 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006224
6225 if (Unqualified) {
6226 LHS = LHS.getUnqualifiedType();
6227 RHS = RHS.getUnqualifiedType();
6228 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006229
Eli Friedman47f77112008-08-22 00:56:42 +00006230 QualType LHSCan = getCanonicalType(LHS),
6231 RHSCan = getCanonicalType(RHS);
6232
6233 // If two types are identical, they are compatible.
6234 if (LHSCan == RHSCan)
6235 return LHS;
6236
John McCall8ccfcb52009-09-24 19:53:00 +00006237 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006238 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6239 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006240 if (LQuals != RQuals) {
6241 // If any of these qualifiers are different, we have a type
6242 // mismatch.
6243 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006244 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6245 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006246 return QualType();
6247
6248 // Exactly one GC qualifier difference is allowed: __strong is
6249 // okay if the other type has no GC qualifier but is an Objective
6250 // C object pointer (i.e. implicitly strong by default). We fix
6251 // this by pretending that the unqualified type was actually
6252 // qualified __strong.
6253 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6254 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6255 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6256
6257 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6258 return QualType();
6259
6260 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6261 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6262 }
6263 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6264 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6265 }
Eli Friedman47f77112008-08-22 00:56:42 +00006266 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006267 }
6268
6269 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006270
Eli Friedmandcca6332009-06-01 01:22:52 +00006271 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6272 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006273
Chris Lattnerfd652912008-01-14 05:45:46 +00006274 // We want to consider the two function types to be the same for these
6275 // comparisons, just force one to the other.
6276 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6277 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006278
6279 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006280 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6281 LHSClass = Type::ConstantArray;
6282 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6283 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006284
John McCall8b07ec22010-05-15 11:32:37 +00006285 // ObjCInterfaces are just specialized ObjCObjects.
6286 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6287 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6288
Nate Begemance4d7fc2008-04-18 23:10:10 +00006289 // Canonicalize ExtVector -> Vector.
6290 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6291 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006292
Chris Lattner95554662008-04-07 05:43:21 +00006293 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006294 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006295 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006296 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006297 // Compatibility is based on the underlying type, not the promotion
6298 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006299 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006300 QualType TINT = ETy->getDecl()->getIntegerType();
6301 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006302 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006303 }
John McCall9dd450b2009-09-21 23:43:11 +00006304 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006305 QualType TINT = ETy->getDecl()->getIntegerType();
6306 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006307 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006308 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006309 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006310 if (OfBlockPointer && !BlockReturnType) {
6311 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6312 return LHS;
6313 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6314 return RHS;
6315 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006316
Eli Friedman47f77112008-08-22 00:56:42 +00006317 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006318 }
Eli Friedman47f77112008-08-22 00:56:42 +00006319
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006320 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006321 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006322#define TYPE(Class, Base)
6323#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006324#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006325#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6326#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6327#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006328 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006329
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006330 case Type::LValueReference:
6331 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006332 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006333 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006334
John McCall8b07ec22010-05-15 11:32:37 +00006335 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006336 case Type::IncompleteArray:
6337 case Type::VariableArray:
6338 case Type::FunctionProto:
6339 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006340 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006341
Chris Lattnerfd652912008-01-14 05:45:46 +00006342 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006343 {
6344 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006345 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6346 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006347 if (Unqualified) {
6348 LHSPointee = LHSPointee.getUnqualifiedType();
6349 RHSPointee = RHSPointee.getUnqualifiedType();
6350 }
6351 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6352 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006353 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006354 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006355 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006356 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006357 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006358 return getPointerType(ResultType);
6359 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006360 case Type::BlockPointer:
6361 {
6362 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006363 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6364 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006365 if (Unqualified) {
6366 LHSPointee = LHSPointee.getUnqualifiedType();
6367 RHSPointee = RHSPointee.getUnqualifiedType();
6368 }
6369 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6370 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006371 if (ResultType.isNull()) return QualType();
6372 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6373 return LHS;
6374 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6375 return RHS;
6376 return getBlockPointerType(ResultType);
6377 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006378 case Type::Atomic:
6379 {
6380 // Merge two pointer types, while trying to preserve typedef info
6381 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6382 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6383 if (Unqualified) {
6384 LHSValue = LHSValue.getUnqualifiedType();
6385 RHSValue = RHSValue.getUnqualifiedType();
6386 }
6387 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6388 Unqualified);
6389 if (ResultType.isNull()) return QualType();
6390 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6391 return LHS;
6392 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6393 return RHS;
6394 return getAtomicType(ResultType);
6395 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006396 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006397 {
6398 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6399 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6400 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6401 return QualType();
6402
6403 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6404 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006405 if (Unqualified) {
6406 LHSElem = LHSElem.getUnqualifiedType();
6407 RHSElem = RHSElem.getUnqualifiedType();
6408 }
6409
6410 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006411 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006412 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6413 return LHS;
6414 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6415 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006416 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6417 ArrayType::ArraySizeModifier(), 0);
6418 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6419 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006420 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6421 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006422 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6423 return LHS;
6424 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6425 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006426 if (LVAT) {
6427 // FIXME: This isn't correct! But tricky to implement because
6428 // the array's size has to be the size of LHS, but the type
6429 // has to be different.
6430 return LHS;
6431 }
6432 if (RVAT) {
6433 // FIXME: This isn't correct! But tricky to implement because
6434 // the array's size has to be the size of RHS, but the type
6435 // has to be different.
6436 return RHS;
6437 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006438 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6439 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006440 return getIncompleteArrayType(ResultType,
6441 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006442 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006443 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006444 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006445 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006446 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006447 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006448 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006449 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006450 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006451 case Type::Complex:
6452 // Distinct complex types are incompatible.
6453 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006454 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006455 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006456 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6457 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006458 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006459 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006460 case Type::ObjCObject: {
6461 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006462 // FIXME: This should be type compatibility, e.g. whether
6463 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006464 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6465 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6466 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006467 return LHS;
6468
Eli Friedman47f77112008-08-22 00:56:42 +00006469 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006470 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006471 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006472 if (OfBlockPointer) {
6473 if (canAssignObjCInterfacesInBlockPointer(
6474 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006475 RHS->getAs<ObjCObjectPointerType>(),
6476 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006477 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006478 return QualType();
6479 }
John McCall9dd450b2009-09-21 23:43:11 +00006480 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6481 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006482 return LHS;
6483
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006484 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006485 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006486 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006487
David Blaikie8a40f702012-01-17 06:56:22 +00006488 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006489}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006490
Fariborz Jahanian97676972011-09-28 21:52:05 +00006491bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6492 const FunctionProtoType *FromFunctionType,
6493 const FunctionProtoType *ToFunctionType) {
6494 if (FromFunctionType->hasAnyConsumedArgs() !=
6495 ToFunctionType->hasAnyConsumedArgs())
6496 return false;
6497 FunctionProtoType::ExtProtoInfo FromEPI =
6498 FromFunctionType->getExtProtoInfo();
6499 FunctionProtoType::ExtProtoInfo ToEPI =
6500 ToFunctionType->getExtProtoInfo();
6501 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6502 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6503 ArgIdx != NumArgs; ++ArgIdx) {
6504 if (FromEPI.ConsumedArguments[ArgIdx] !=
6505 ToEPI.ConsumedArguments[ArgIdx])
6506 return false;
6507 }
6508 return true;
6509}
6510
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006511/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6512/// 'RHS' attributes and returns the merged version; including for function
6513/// return types.
6514QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6515 QualType LHSCan = getCanonicalType(LHS),
6516 RHSCan = getCanonicalType(RHS);
6517 // If two types are identical, they are compatible.
6518 if (LHSCan == RHSCan)
6519 return LHS;
6520 if (RHSCan->isFunctionType()) {
6521 if (!LHSCan->isFunctionType())
6522 return QualType();
6523 QualType OldReturnType =
6524 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6525 QualType NewReturnType =
6526 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6527 QualType ResReturnType =
6528 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6529 if (ResReturnType.isNull())
6530 return QualType();
6531 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6532 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6533 // In either case, use OldReturnType to build the new function type.
6534 const FunctionType *F = LHS->getAs<FunctionType>();
6535 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006536 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6537 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006538 QualType ResultType
6539 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006540 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006541 return ResultType;
6542 }
6543 }
6544 return QualType();
6545 }
6546
6547 // If the qualifiers are different, the types can still be merged.
6548 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6549 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6550 if (LQuals != RQuals) {
6551 // If any of these qualifiers are different, we have a type mismatch.
6552 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6553 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6554 return QualType();
6555
6556 // Exactly one GC qualifier difference is allowed: __strong is
6557 // okay if the other type has no GC qualifier but is an Objective
6558 // C object pointer (i.e. implicitly strong by default). We fix
6559 // this by pretending that the unqualified type was actually
6560 // qualified __strong.
6561 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6562 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6563 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6564
6565 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6566 return QualType();
6567
6568 if (GC_L == Qualifiers::Strong)
6569 return LHS;
6570 if (GC_R == Qualifiers::Strong)
6571 return RHS;
6572 return QualType();
6573 }
6574
6575 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6576 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6577 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6578 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6579 if (ResQT == LHSBaseQT)
6580 return LHS;
6581 if (ResQT == RHSBaseQT)
6582 return RHS;
6583 }
6584 return QualType();
6585}
6586
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006587//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006588// Integer Predicates
6589//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006590
Jay Foad39c79802011-01-12 09:06:06 +00006591unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006592 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006593 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006594 if (T->isBooleanType())
6595 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006596 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006597 return (unsigned)getTypeSize(T);
6598}
6599
6600QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006601 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006602
6603 // Turn <4 x signed int> -> <4 x unsigned int>
6604 if (const VectorType *VTy = T->getAs<VectorType>())
6605 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006606 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006607
6608 // For enums, we return the unsigned version of the base type.
6609 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006610 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006611
6612 const BuiltinType *BTy = T->getAs<BuiltinType>();
6613 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006614 switch (BTy->getKind()) {
6615 case BuiltinType::Char_S:
6616 case BuiltinType::SChar:
6617 return UnsignedCharTy;
6618 case BuiltinType::Short:
6619 return UnsignedShortTy;
6620 case BuiltinType::Int:
6621 return UnsignedIntTy;
6622 case BuiltinType::Long:
6623 return UnsignedLongTy;
6624 case BuiltinType::LongLong:
6625 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006626 case BuiltinType::Int128:
6627 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006628 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006629 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006630 }
6631}
6632
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006633ASTMutationListener::~ASTMutationListener() { }
6634
Chris Lattnerecd79c62009-06-14 00:45:47 +00006635
6636//===----------------------------------------------------------------------===//
6637// Builtin Type Computation
6638//===----------------------------------------------------------------------===//
6639
6640/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006641/// pointer over the consumed characters. This returns the resultant type. If
6642/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6643/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6644/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006645///
6646/// RequiresICE is filled in on return to indicate whether the value is required
6647/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006648static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006649 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006650 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006651 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006652 // Modifiers.
6653 int HowLong = 0;
6654 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006655 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006656
Chris Lattnerdc226c22010-10-01 22:42:38 +00006657 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006658 bool Done = false;
6659 while (!Done) {
6660 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006661 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006662 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006663 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006664 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006665 case 'S':
6666 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6667 assert(!Signed && "Can't use 'S' modifier multiple times!");
6668 Signed = true;
6669 break;
6670 case 'U':
6671 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6672 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6673 Unsigned = true;
6674 break;
6675 case 'L':
6676 assert(HowLong <= 2 && "Can't have LLLL modifier");
6677 ++HowLong;
6678 break;
6679 }
6680 }
6681
6682 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006683
Chris Lattnerecd79c62009-06-14 00:45:47 +00006684 // Read the base type.
6685 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006686 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006687 case 'v':
6688 assert(HowLong == 0 && !Signed && !Unsigned &&
6689 "Bad modifiers used with 'v'!");
6690 Type = Context.VoidTy;
6691 break;
6692 case 'f':
6693 assert(HowLong == 0 && !Signed && !Unsigned &&
6694 "Bad modifiers used with 'f'!");
6695 Type = Context.FloatTy;
6696 break;
6697 case 'd':
6698 assert(HowLong < 2 && !Signed && !Unsigned &&
6699 "Bad modifiers used with 'd'!");
6700 if (HowLong)
6701 Type = Context.LongDoubleTy;
6702 else
6703 Type = Context.DoubleTy;
6704 break;
6705 case 's':
6706 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6707 if (Unsigned)
6708 Type = Context.UnsignedShortTy;
6709 else
6710 Type = Context.ShortTy;
6711 break;
6712 case 'i':
6713 if (HowLong == 3)
6714 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6715 else if (HowLong == 2)
6716 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6717 else if (HowLong == 1)
6718 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6719 else
6720 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6721 break;
6722 case 'c':
6723 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6724 if (Signed)
6725 Type = Context.SignedCharTy;
6726 else if (Unsigned)
6727 Type = Context.UnsignedCharTy;
6728 else
6729 Type = Context.CharTy;
6730 break;
6731 case 'b': // boolean
6732 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6733 Type = Context.BoolTy;
6734 break;
6735 case 'z': // size_t.
6736 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6737 Type = Context.getSizeType();
6738 break;
6739 case 'F':
6740 Type = Context.getCFConstantStringType();
6741 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006742 case 'G':
6743 Type = Context.getObjCIdType();
6744 break;
6745 case 'H':
6746 Type = Context.getObjCSelType();
6747 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006748 case 'a':
6749 Type = Context.getBuiltinVaListType();
6750 assert(!Type.isNull() && "builtin va list type not initialized!");
6751 break;
6752 case 'A':
6753 // This is a "reference" to a va_list; however, what exactly
6754 // this means depends on how va_list is defined. There are two
6755 // different kinds of va_list: ones passed by value, and ones
6756 // passed by reference. An example of a by-value va_list is
6757 // x86, where va_list is a char*. An example of by-ref va_list
6758 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6759 // we want this argument to be a char*&; for x86-64, we want
6760 // it to be a __va_list_tag*.
6761 Type = Context.getBuiltinVaListType();
6762 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006763 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006764 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006765 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006766 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006767 break;
6768 case 'V': {
6769 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006770 unsigned NumElements = strtoul(Str, &End, 10);
6771 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006772 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006773
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006774 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6775 RequiresICE, false);
6776 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006777
6778 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006779 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006780 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006781 break;
6782 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006783 case 'E': {
6784 char *End;
6785
6786 unsigned NumElements = strtoul(Str, &End, 10);
6787 assert(End != Str && "Missing vector size");
6788
6789 Str = End;
6790
6791 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6792 false);
6793 Type = Context.getExtVectorType(ElementType, NumElements);
6794 break;
6795 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006796 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006797 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6798 false);
6799 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006800 Type = Context.getComplexType(ElementType);
6801 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006802 }
6803 case 'Y' : {
6804 Type = Context.getPointerDiffType();
6805 break;
6806 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006807 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006808 Type = Context.getFILEType();
6809 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006810 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006811 return QualType();
6812 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006813 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006814 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006815 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006816 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006817 else
6818 Type = Context.getjmp_bufType();
6819
Mike Stump2adb4da2009-07-28 23:47:15 +00006820 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006821 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006822 return QualType();
6823 }
6824 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006825 case 'K':
6826 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6827 Type = Context.getucontext_tType();
6828
6829 if (Type.isNull()) {
6830 Error = ASTContext::GE_Missing_ucontext;
6831 return QualType();
6832 }
6833 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006834 }
Mike Stump11289f42009-09-09 15:08:12 +00006835
Chris Lattnerdc226c22010-10-01 22:42:38 +00006836 // If there are modifiers and if we're allowed to parse them, go for it.
6837 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006838 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006839 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006840 default: Done = true; --Str; break;
6841 case '*':
6842 case '&': {
6843 // Both pointers and references can have their pointee types
6844 // qualified with an address space.
6845 char *End;
6846 unsigned AddrSpace = strtoul(Str, &End, 10);
6847 if (End != Str && AddrSpace != 0) {
6848 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6849 Str = End;
6850 }
6851 if (c == '*')
6852 Type = Context.getPointerType(Type);
6853 else
6854 Type = Context.getLValueReferenceType(Type);
6855 break;
6856 }
6857 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6858 case 'C':
6859 Type = Type.withConst();
6860 break;
6861 case 'D':
6862 Type = Context.getVolatileType(Type);
6863 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006864 case 'R':
6865 Type = Type.withRestrict();
6866 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006867 }
6868 }
Chris Lattner84733392010-10-01 07:13:18 +00006869
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006870 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006871 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006872
Chris Lattnerecd79c62009-06-14 00:45:47 +00006873 return Type;
6874}
6875
6876/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006877QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006878 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006879 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006880 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006881
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006882 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006883
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006884 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006885 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006886 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6887 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006888 if (Error != GE_None)
6889 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006890
6891 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6892
Chris Lattnerecd79c62009-06-14 00:45:47 +00006893 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006894 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006895 if (Error != GE_None)
6896 return QualType();
6897
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006898 // If this argument is required to be an IntegerConstantExpression and the
6899 // caller cares, fill in the bitmask we return.
6900 if (RequiresICE && IntegerConstantArgs)
6901 *IntegerConstantArgs |= 1 << ArgTypes.size();
6902
Chris Lattnerecd79c62009-06-14 00:45:47 +00006903 // Do array -> pointer decay. The builtin should use the decayed type.
6904 if (Ty->isArrayType())
6905 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006906
Chris Lattnerecd79c62009-06-14 00:45:47 +00006907 ArgTypes.push_back(Ty);
6908 }
6909
6910 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6911 "'.' should only occur at end of builtin type list!");
6912
John McCall991eb4b2010-12-21 00:44:39 +00006913 FunctionType::ExtInfo EI;
6914 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6915
6916 bool Variadic = (TypeStr[0] == '.');
6917
6918 // We really shouldn't be making a no-proto type here, especially in C++.
6919 if (ArgTypes.empty() && Variadic)
6920 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006921
John McCalldb40c7f2010-12-14 08:05:40 +00006922 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006923 EPI.ExtInfo = EI;
6924 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006925
6926 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006927}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006928
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006929GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6930 GVALinkage External = GVA_StrongExternal;
6931
6932 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006933 switch (L) {
6934 case NoLinkage:
6935 case InternalLinkage:
6936 case UniqueExternalLinkage:
6937 return GVA_Internal;
6938
6939 case ExternalLinkage:
6940 switch (FD->getTemplateSpecializationKind()) {
6941 case TSK_Undeclared:
6942 case TSK_ExplicitSpecialization:
6943 External = GVA_StrongExternal;
6944 break;
6945
6946 case TSK_ExplicitInstantiationDefinition:
6947 return GVA_ExplicitTemplateInstantiation;
6948
6949 case TSK_ExplicitInstantiationDeclaration:
6950 case TSK_ImplicitInstantiation:
6951 External = GVA_TemplateInstantiation;
6952 break;
6953 }
6954 }
6955
6956 if (!FD->isInlined())
6957 return External;
6958
David Blaikiebbafb8a2012-03-11 07:00:24 +00006959 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006960 // GNU or C99 inline semantics. Determine whether this symbol should be
6961 // externally visible.
6962 if (FD->isInlineDefinitionExternallyVisible())
6963 return External;
6964
6965 // C99 inline semantics, where the symbol is not externally visible.
6966 return GVA_C99Inline;
6967 }
6968
6969 // C++0x [temp.explicit]p9:
6970 // [ Note: The intent is that an inline function that is the subject of
6971 // an explicit instantiation declaration will still be implicitly
6972 // instantiated when used so that the body can be considered for
6973 // inlining, but that no out-of-line copy of the inline function would be
6974 // generated in the translation unit. -- end note ]
6975 if (FD->getTemplateSpecializationKind()
6976 == TSK_ExplicitInstantiationDeclaration)
6977 return GVA_C99Inline;
6978
6979 return GVA_CXXInline;
6980}
6981
6982GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6983 // If this is a static data member, compute the kind of template
6984 // specialization. Otherwise, this variable is not part of a
6985 // template.
6986 TemplateSpecializationKind TSK = TSK_Undeclared;
6987 if (VD->isStaticDataMember())
6988 TSK = VD->getTemplateSpecializationKind();
6989
6990 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006991 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006992 VD->getType()->getLinkage() == UniqueExternalLinkage)
6993 L = UniqueExternalLinkage;
6994
6995 switch (L) {
6996 case NoLinkage:
6997 case InternalLinkage:
6998 case UniqueExternalLinkage:
6999 return GVA_Internal;
7000
7001 case ExternalLinkage:
7002 switch (TSK) {
7003 case TSK_Undeclared:
7004 case TSK_ExplicitSpecialization:
7005 return GVA_StrongExternal;
7006
7007 case TSK_ExplicitInstantiationDeclaration:
7008 llvm_unreachable("Variable should not be instantiated");
7009 // Fall through to treat this like any other instantiation.
7010
7011 case TSK_ExplicitInstantiationDefinition:
7012 return GVA_ExplicitTemplateInstantiation;
7013
7014 case TSK_ImplicitInstantiation:
7015 return GVA_TemplateInstantiation;
7016 }
7017 }
7018
David Blaikie8a40f702012-01-17 06:56:22 +00007019 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007020}
7021
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007022bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7024 if (!VD->isFileVarDecl())
7025 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007026 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007027 return false;
7028
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007029 // Weak references don't produce any output by themselves.
7030 if (D->hasAttr<WeakRefAttr>())
7031 return false;
7032
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007033 // Aliases and used decls are required.
7034 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7035 return true;
7036
7037 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7038 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007039 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007040 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007041
7042 // Constructors and destructors are required.
7043 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7044 return true;
7045
7046 // The key function for a class is required.
7047 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7048 const CXXRecordDecl *RD = MD->getParent();
7049 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7050 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7051 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7052 return true;
7053 }
7054 }
7055
7056 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7057
7058 // static, static inline, always_inline, and extern inline functions can
7059 // always be deferred. Normal inline functions can be deferred in C99/C++.
7060 // Implicit template instantiations can also be deferred in C++.
7061 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007062 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007063 return false;
7064 return true;
7065 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007066
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007067 const VarDecl *VD = cast<VarDecl>(D);
7068 assert(VD->isFileVarDecl() && "Expected file scoped var");
7069
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007070 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7071 return false;
7072
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007073 // Structs that have non-trivial constructors or destructors are required.
7074
7075 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007076 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007077 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7078 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007079 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7080 RD->hasTrivialCopyConstructor() &&
7081 RD->hasTrivialMoveConstructor() &&
7082 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007083 return true;
7084 }
7085 }
7086
7087 GVALinkage L = GetGVALinkageForVariable(VD);
7088 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7089 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7090 return false;
7091 }
7092
7093 return true;
7094}
Charles Davis53c59df2010-08-16 03:33:14 +00007095
Charles Davis99202b32010-11-09 18:04:24 +00007096CallingConv ASTContext::getDefaultMethodCallConv() {
7097 // Pass through to the C++ ABI object
7098 return ABI->getDefaultMethodCallConv();
7099}
7100
Jay Foad39c79802011-01-12 09:06:06 +00007101bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007102 // Pass through to the C++ ABI object
7103 return ABI->isNearlyEmpty(RD);
7104}
7105
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007106MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007107 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007108 case CXXABI_ARM:
7109 case CXXABI_Itanium:
7110 return createItaniumMangleContext(*this, getDiagnostics());
7111 case CXXABI_Microsoft:
7112 return createMicrosoftMangleContext(*this, getDiagnostics());
7113 }
David Blaikie83d382b2011-09-23 05:06:16 +00007114 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007115}
7116
Charles Davis53c59df2010-08-16 03:33:14 +00007117CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007118
7119size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007120 return ASTRecordLayouts.getMemorySize()
7121 + llvm::capacity_in_bytes(ObjCLayouts)
7122 + llvm::capacity_in_bytes(KeyFunctions)
7123 + llvm::capacity_in_bytes(ObjCImpls)
7124 + llvm::capacity_in_bytes(BlockVarCopyInits)
7125 + llvm::capacity_in_bytes(DeclAttrs)
7126 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7127 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7128 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7129 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7130 + llvm::capacity_in_bytes(OverriddenMethods)
7131 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007132 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007133 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007134}
Ted Kremenek540017e2011-10-06 05:00:56 +00007135
Douglas Gregor63798542012-02-20 19:44:39 +00007136unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7137 CXXRecordDecl *Lambda = CallOperator->getParent();
7138 return LambdaMangleContexts[Lambda->getDeclContext()]
7139 .getManglingNumber(CallOperator);
7140}
7141
7142
Ted Kremenek540017e2011-10-06 05:00:56 +00007143void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7144 ParamIndices[D] = index;
7145}
7146
7147unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7148 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7149 assert(I != ParamIndices.end() &&
7150 "ParmIndices lacks entry set by ParmVarDecl");
7151 return I->second;
7152}