blob: 30e42349564df0b3f38756b55c65067ee3310439 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000025#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000027#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000028#include "RecordLayoutBuilder.h"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
32enum FloatingRank {
33 FloatRank, DoubleRank, LongDoubleRank
34};
35
Chris Lattner61710852008-10-05 17:34:18 +000036ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
37 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000038 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000039 Builtin::Context &builtins,
40 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000041 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000042 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
43 sigjmp_bufDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000044 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
45 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000046 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000047 ObjCIdRedefinitionType = QualType();
48 ObjCClassRedefinitionType = QualType();
Daniel Dunbare91593e2008-08-11 04:54:23 +000049 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000050 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000051 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000052}
53
Reid Spencer5f016e22007-07-11 17:01:13 +000054ASTContext::~ASTContext() {
55 // Deallocate all the types.
56 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000057 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000058 Types.pop_back();
59 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000060
Nuno Lopesb74668e2008-12-17 22:30:25 +000061 {
62 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
63 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
64 while (I != E) {
65 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
66 delete R;
67 }
68 }
69
70 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000071 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
72 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000073 while (I != E) {
74 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
75 delete R;
76 }
77 }
78
Douglas Gregorab452ba2009-03-26 23:50:42 +000079 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000080 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
81 NNS = NestedNameSpecifiers.begin(),
82 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000083 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000084 /* Increment in loop */)
85 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000086
87 if (GlobalNestedNameSpecifier)
88 GlobalNestedNameSpecifier->Destroy(*this);
89
Eli Friedmanb26153c2008-05-27 03:08:09 +000090 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000091}
92
Douglas Gregor2cf26342009-04-09 22:27:44 +000093void
94ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
95 ExternalSource.reset(Source.take());
96}
97
Reid Spencer5f016e22007-07-11 17:01:13 +000098void ASTContext::PrintStats() const {
99 fprintf(stderr, "*** AST Context Stats:\n");
100 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000101
Douglas Gregordbe833d2009-05-26 14:40:08 +0000102 unsigned counts[] = {
103#define TYPE(Name, Parent) 0,
104#define ABSTRACT_TYPE(Name, Parent)
105#include "clang/AST/TypeNodes.def"
106 0 // Extra
107 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
110 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000111 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 }
113
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114 unsigned Idx = 0;
115 unsigned TotalBytes = 0;
116#define TYPE(Name, Parent) \
117 if (counts[Idx]) \
118 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
119 TotalBytes += counts[Idx] * sizeof(Name##Type); \
120 ++Idx;
121#define ABSTRACT_TYPE(Name, Parent)
122#include "clang/AST/TypeNodes.def"
123
124 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000125
126 if (ExternalSource.get()) {
127 fprintf(stderr, "\n");
128 ExternalSource->PrintStats();
129 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000130}
131
132
133void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000134 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000135}
136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137void ASTContext::InitBuiltinTypes() {
138 assert(VoidTy.isNull() && "Context reinitialized?");
139
140 // C99 6.2.5p19.
141 InitBuiltinType(VoidTy, BuiltinType::Void);
142
143 // C99 6.2.5p2.
144 InitBuiltinType(BoolTy, BuiltinType::Bool);
145 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000146 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 InitBuiltinType(CharTy, BuiltinType::Char_S);
148 else
149 InitBuiltinType(CharTy, BuiltinType::Char_U);
150 // C99 6.2.5p4.
151 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
152 InitBuiltinType(ShortTy, BuiltinType::Short);
153 InitBuiltinType(IntTy, BuiltinType::Int);
154 InitBuiltinType(LongTy, BuiltinType::Long);
155 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
156
157 // C99 6.2.5p6.
158 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
159 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
160 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
161 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
162 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
163
164 // C99 6.2.5p10.
165 InitBuiltinType(FloatTy, BuiltinType::Float);
166 InitBuiltinType(DoubleTy, BuiltinType::Double);
167 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000168
Chris Lattner2df9ced2009-04-30 02:43:43 +0000169 // GNU extension, 128-bit integers.
170 InitBuiltinType(Int128Ty, BuiltinType::Int128);
171 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
172
Chris Lattner3a250322009-02-26 23:43:47 +0000173 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
174 InitBuiltinType(WCharTy, BuiltinType::WChar);
175 else // C99
176 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000177
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000178 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
179 InitBuiltinType(Char16Ty, BuiltinType::Char16);
180 else // C99
181 Char16Ty = getFromTargetType(Target.getChar16Type());
182
183 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
184 InitBuiltinType(Char32Ty, BuiltinType::Char32);
185 else // C99
186 Char32Ty = getFromTargetType(Target.getChar32Type());
187
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000188 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000189 InitBuiltinType(OverloadTy, BuiltinType::Overload);
190
191 // Placeholder type for type-dependent expressions whose type is
192 // completely unknown. No code should ever check a type against
193 // DependentTy and users should never see it; however, it is here to
194 // help diagnose failures to properly check for type-dependent
195 // expressions.
196 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197
Anders Carlssone89d1592009-06-26 18:41:36 +0000198 // Placeholder type for C++0x auto declarations whose real type has
199 // not yet been deduced.
200 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
201
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 // C99 6.2.5p11.
203 FloatComplexTy = getComplexType(FloatTy);
204 DoubleComplexTy = getComplexType(DoubleTy);
205 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000206
Steve Naroff7e219e42007-10-15 14:41:52 +0000207 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000208
Steve Naroffde2e22d2009-07-15 18:40:39 +0000209 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
210 ObjCIdTypedefType = QualType();
211 ObjCClassTypedefType = QualType();
212
213 // Builtin types for 'id' and 'Class'.
214 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
215 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000216
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000218
219 // void * type
220 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000221
222 // nullptr type (C++0x 2.14.7)
223 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000224}
225
Douglas Gregor7caa6822009-07-24 20:34:43 +0000226VarDecl *ASTContext::getInstantiatedFromStaticDataMember(VarDecl *Var) {
227 assert(Var->isStaticDataMember() && "Not a static data member");
228 llvm::DenseMap<VarDecl *, VarDecl *>::iterator Pos
229 = InstantiatedFromStaticDataMember.find(Var);
230 if (Pos == InstantiatedFromStaticDataMember.end())
231 return 0;
232
233 return Pos->second;
234}
235
236void
237ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) {
238 assert(Inst->isStaticDataMember() && "Not a static data member");
239 assert(Tmpl->isStaticDataMember() && "Not a static data member");
240 assert(!InstantiatedFromStaticDataMember[Inst] &&
241 "Already noted what static data member was instantiated from");
242 InstantiatedFromStaticDataMember[Inst] = Tmpl;
243}
244
Anders Carlsson0d8df782009-08-29 19:37:28 +0000245UnresolvedUsingDecl *
246ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
247 llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::iterator Pos
248 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
249 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
250 return 0;
251
252 return Pos->second;
253}
254
255void
256ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
257 UnresolvedUsingDecl *UUD) {
258 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
259 "Already noted what using decl what instantiated from");
260 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
261}
262
Anders Carlssond8b285f2009-09-01 04:26:58 +0000263FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
264 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
265 = InstantiatedFromUnnamedFieldDecl.find(Field);
266 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
267 return 0;
268
269 return Pos->second;
270}
271
272void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
273 FieldDecl *Tmpl) {
274 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
275 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
276 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
277 "Already noted what unnamed field was instantiated from");
278
279 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
280}
281
Douglas Gregor2e222532009-07-02 17:08:52 +0000282namespace {
283 class BeforeInTranslationUnit
284 : std::binary_function<SourceRange, SourceRange, bool> {
285 SourceManager *SourceMgr;
286
287 public:
288 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
289
290 bool operator()(SourceRange X, SourceRange Y) {
291 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
292 }
293 };
294}
295
296/// \brief Determine whether the given comment is a Doxygen-style comment.
297///
298/// \param Start the start of the comment text.
299///
300/// \param End the end of the comment text.
301///
302/// \param Member whether we want to check whether this is a member comment
303/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
304/// we only return true when we find a non-member comment.
305static bool
306isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
307 bool Member = false) {
308 const char *BufferStart
309 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
310 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
311 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
312
313 if (End - Start < 4)
314 return false;
315
316 assert(Start[0] == '/' && "Not a comment?");
317 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
318 return false;
319 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
320 return false;
321
322 return (Start[3] == '<') == Member;
323}
324
325/// \brief Retrieve the comment associated with the given declaration, if
326/// it has one.
327const char *ASTContext::getCommentForDecl(const Decl *D) {
328 if (!D)
329 return 0;
330
331 // Check whether we have cached a comment string for this declaration
332 // already.
333 llvm::DenseMap<const Decl *, std::string>::iterator Pos
334 = DeclComments.find(D);
335 if (Pos != DeclComments.end())
336 return Pos->second.c_str();
337
338 // If we have an external AST source and have not yet loaded comments from
339 // that source, do so now.
340 if (ExternalSource && !LoadedExternalComments) {
341 std::vector<SourceRange> LoadedComments;
342 ExternalSource->ReadComments(LoadedComments);
343
344 if (!LoadedComments.empty())
345 Comments.insert(Comments.begin(), LoadedComments.begin(),
346 LoadedComments.end());
347
348 LoadedExternalComments = true;
349 }
350
351 // If there are no comments anywhere, we won't find anything.
352 if (Comments.empty())
353 return 0;
354
355 // If the declaration doesn't map directly to a location in a file, we
356 // can't find the comment.
357 SourceLocation DeclStartLoc = D->getLocStart();
358 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
359 return 0;
360
361 // Find the comment that occurs just before this declaration.
362 std::vector<SourceRange>::iterator LastComment
363 = std::lower_bound(Comments.begin(), Comments.end(),
364 SourceRange(DeclStartLoc),
365 BeforeInTranslationUnit(&SourceMgr));
366
367 // Decompose the location for the start of the declaration and find the
368 // beginning of the file buffer.
369 std::pair<FileID, unsigned> DeclStartDecomp
370 = SourceMgr.getDecomposedLoc(DeclStartLoc);
371 const char *FileBufferStart
372 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
373
374 // First check whether we have a comment for a member.
375 if (LastComment != Comments.end() &&
376 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
377 isDoxygenComment(SourceMgr, *LastComment, true)) {
378 std::pair<FileID, unsigned> LastCommentEndDecomp
379 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
380 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
381 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
382 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
383 LastCommentEndDecomp.second)) {
384 // The Doxygen member comment comes after the declaration starts and
385 // is on the same line and in the same file as the declaration. This
386 // is the comment we want.
387 std::string &Result = DeclComments[D];
388 Result.append(FileBufferStart +
389 SourceMgr.getFileOffset(LastComment->getBegin()),
390 FileBufferStart + LastCommentEndDecomp.second + 1);
391 return Result.c_str();
392 }
393 }
394
395 if (LastComment == Comments.begin())
396 return 0;
397 --LastComment;
398
399 // Decompose the end of the comment.
400 std::pair<FileID, unsigned> LastCommentEndDecomp
401 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
402
403 // If the comment and the declaration aren't in the same file, then they
404 // aren't related.
405 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
406 return 0;
407
408 // Check that we actually have a Doxygen comment.
409 if (!isDoxygenComment(SourceMgr, *LastComment))
410 return 0;
411
412 // Compute the starting line for the declaration and for the end of the
413 // comment (this is expensive).
414 unsigned DeclStartLine
415 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
416 unsigned CommentEndLine
417 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
418 LastCommentEndDecomp.second);
419
420 // If the comment does not end on the line prior to the declaration, then
421 // the comment is not associated with the declaration at all.
422 if (CommentEndLine + 1 != DeclStartLine)
423 return 0;
424
425 // We have a comment, but there may be more comments on the previous lines.
426 // Keep looking so long as the comments are still Doxygen comments and are
427 // still adjacent.
428 unsigned ExpectedLine
429 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
430 std::vector<SourceRange>::iterator FirstComment = LastComment;
431 while (FirstComment != Comments.begin()) {
432 // Look at the previous comment
433 --FirstComment;
434 std::pair<FileID, unsigned> Decomp
435 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
436
437 // If this previous comment is in a different file, we're done.
438 if (Decomp.first != DeclStartDecomp.first) {
439 ++FirstComment;
440 break;
441 }
442
443 // If this comment is not a Doxygen comment, we're done.
444 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
445 ++FirstComment;
446 break;
447 }
448
449 // If the line number is not what we expected, we're done.
450 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
451 if (Line != ExpectedLine) {
452 ++FirstComment;
453 break;
454 }
455
456 // Set the next expected line number.
457 ExpectedLine
458 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
459 }
460
461 // The iterator range [FirstComment, LastComment] contains all of the
462 // BCPL comments that, together, are associated with this declaration.
463 // Form a single comment block string for this declaration that concatenates
464 // all of these comments.
465 std::string &Result = DeclComments[D];
466 while (FirstComment != LastComment) {
467 std::pair<FileID, unsigned> DecompStart
468 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
469 std::pair<FileID, unsigned> DecompEnd
470 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
471 Result.append(FileBufferStart + DecompStart.second,
472 FileBufferStart + DecompEnd.second + 1);
473 ++FirstComment;
474 }
475
476 // Append the last comment line.
477 Result.append(FileBufferStart +
478 SourceMgr.getFileOffset(LastComment->getBegin()),
479 FileBufferStart + LastCommentEndDecomp.second + 1);
480 return Result.c_str();
481}
482
Chris Lattner464175b2007-07-18 17:52:12 +0000483//===----------------------------------------------------------------------===//
484// Type Sizing and Analysis
485//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000486
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000487/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
488/// scalar floating point type.
489const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
490 const BuiltinType *BT = T->getAsBuiltinType();
491 assert(BT && "Not a floating point type!");
492 switch (BT->getKind()) {
493 default: assert(0 && "Not a floating point type!");
494 case BuiltinType::Float: return Target.getFloatFormat();
495 case BuiltinType::Double: return Target.getDoubleFormat();
496 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
497 }
498}
499
Chris Lattneraf707ab2009-01-24 21:53:27 +0000500/// getDeclAlign - Return a conservative estimate of the alignment of the
501/// specified decl. Note that bitfields do not have a valid alignment, so
502/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000503unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000504 unsigned Align = Target.getCharWidth();
505
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000506 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000507 Align = std::max(Align, AA->getAlignment());
508
Chris Lattneraf707ab2009-01-24 21:53:27 +0000509 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
510 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000511 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000512 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000513 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000514 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
515 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000516 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
517 T = cast<ArrayType>(T)->getElementType();
518
519 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
520 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000521 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000522
523 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000524}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000525
Chris Lattnera7674d82007-07-13 22:13:22 +0000526/// getTypeSize - Return the size of the specified type, in bits. This method
527/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000528std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000529ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000530 uint64_t Width=0;
531 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000532 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000533#define TYPE(Class, Base)
534#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000535#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000536#define DEPENDENT_TYPE(Class, Base) case Type::Class:
537#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000538 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000539 break;
540
Chris Lattner692233e2007-07-13 22:27:08 +0000541 case Type::FunctionNoProto:
542 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000543 // GCC extension: alignof(function) = 32 bits
544 Width = 0;
545 Align = 32;
546 break;
547
Douglas Gregor72564e72009-02-26 23:50:07 +0000548 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000549 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000550 Width = 0;
551 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
552 break;
553
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000554 case Type::ConstantArrayWithExpr:
555 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000556 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000557 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000558
Chris Lattner98be4942008-03-05 18:54:05 +0000559 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000560 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000561 Align = EltInfo.second;
562 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000563 }
Nate Begeman213541a2008-04-18 23:10:10 +0000564 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000565 case Type::Vector: {
566 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000567 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000568 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000569 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000570 // If the alignment is not a power of 2, round up to the next power of 2.
571 // This happens for non-power-of-2 length vectors.
572 // FIXME: this should probably be a target property.
573 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000574 break;
575 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000576
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000577 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000578 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000579 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000580 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000581 // GCC extension: alignof(void) = 8 bits.
582 Width = 0;
583 Align = 8;
584 break;
585
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000586 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000587 Width = Target.getBoolWidth();
588 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000589 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000590 case BuiltinType::Char_S:
591 case BuiltinType::Char_U:
592 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000593 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000594 Width = Target.getCharWidth();
595 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000596 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000597 case BuiltinType::WChar:
598 Width = Target.getWCharWidth();
599 Align = Target.getWCharAlign();
600 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000601 case BuiltinType::Char16:
602 Width = Target.getChar16Width();
603 Align = Target.getChar16Align();
604 break;
605 case BuiltinType::Char32:
606 Width = Target.getChar32Width();
607 Align = Target.getChar32Align();
608 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000609 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000610 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000611 Width = Target.getShortWidth();
612 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000613 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000614 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000615 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000616 Width = Target.getIntWidth();
617 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000618 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000619 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000620 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000621 Width = Target.getLongWidth();
622 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000623 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000624 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000625 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000626 Width = Target.getLongLongWidth();
627 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000628 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000629 case BuiltinType::Int128:
630 case BuiltinType::UInt128:
631 Width = 128;
632 Align = 128; // int128_t is 128-bit aligned on all targets.
633 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000635 Width = Target.getFloatWidth();
636 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000637 break;
638 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000639 Width = Target.getDoubleWidth();
640 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
642 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000643 Width = Target.getLongDoubleWidth();
644 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000646 case BuiltinType::NullPtr:
647 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
648 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000649 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000650 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000651 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000652 case Type::FixedWidthInt:
653 // FIXME: This isn't precisely correct; the width/alignment should depend
654 // on the available types for the target
655 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000656 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000657 Align = Width;
658 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000659 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000660 // FIXME: Pointers into different addr spaces could have different sizes and
661 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000662 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000663 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000664 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000665 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000666 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000667 case Type::BlockPointer: {
668 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
669 Width = Target.getPointerWidth(AS);
670 Align = Target.getPointerAlign(AS);
671 break;
672 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000673 case Type::Pointer: {
674 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000675 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000676 Align = Target.getPointerAlign(AS);
677 break;
678 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000679 case Type::LValueReference:
680 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000681 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000682 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 // FIXME: This is wrong for struct layout: a reference in a struct has
684 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000685 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000686 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000687 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
688 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
689 // If we ever want to support other ABIs this needs to be abstracted.
690
Sebastian Redlf30208a2009-01-24 21:16:55 +0000691 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000692 std::pair<uint64_t, unsigned> PtrDiffInfo =
693 getTypeInfo(getPointerDiffType());
694 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000695 if (Pointee->isFunctionType())
696 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000697 Align = PtrDiffInfo.second;
698 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000699 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000700 case Type::Complex: {
701 // Complex types have the same alignment as their elements, but twice the
702 // size.
703 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000704 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000705 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000706 Align = EltInfo.second;
707 break;
708 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000709 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000710 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000711 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
712 Width = Layout.getSize();
713 Align = Layout.getAlignment();
714 break;
715 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000716 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000717 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000718 const TagType *TT = cast<TagType>(T);
719
720 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000721 Width = 1;
722 Align = 1;
723 break;
724 }
725
Daniel Dunbar1d751182008-11-08 05:48:37 +0000726 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000727 return getTypeInfo(ET->getDecl()->getIntegerType());
728
Daniel Dunbar1d751182008-11-08 05:48:37 +0000729 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000730 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
731 Width = Layout.getSize();
732 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000733 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000734 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000735
John McCall7da24312009-09-05 00:15:47 +0000736 case Type::Elaborated: {
737 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType().getTypePtr());
738 }
739
Douglas Gregor18857642009-04-30 17:32:17 +0000740 case Type::Typedef: {
741 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000742 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000743 Align = Aligned->getAlignment();
744 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
745 } else
746 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000747 break;
Chris Lattner71763312008-04-06 22:05:18 +0000748 }
Douglas Gregor18857642009-04-30 17:32:17 +0000749
750 case Type::TypeOfExpr:
751 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
752 .getTypePtr());
753
754 case Type::TypeOf:
755 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
756
Anders Carlsson395b4752009-06-24 19:06:50 +0000757 case Type::Decltype:
758 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
759 .getTypePtr());
760
Douglas Gregor18857642009-04-30 17:32:17 +0000761 case Type::QualifiedName:
762 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
763
764 case Type::TemplateSpecialization:
765 assert(getCanonicalType(T) != T &&
766 "Cannot request the size of a dependent type");
767 // FIXME: this is likely to be wrong once we support template
768 // aliases, since a template alias could refer to a typedef that
769 // has an __aligned__ attribute on it.
770 return getTypeInfo(getCanonicalType(T));
771 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000772
Chris Lattner464175b2007-07-18 17:52:12 +0000773 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000774 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000775}
776
Chris Lattner34ebde42009-01-27 18:08:34 +0000777/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
778/// type for the current target in bits. This can be different than the ABI
779/// alignment in cases where it is beneficial for performance to overalign
780/// a data type.
781unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
782 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000783
784 // Double and long long should be naturally aligned if possible.
785 if (const ComplexType* CT = T->getAsComplexType())
786 T = CT->getElementType().getTypePtr();
787 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
788 T->isSpecificBuiltinType(BuiltinType::LongLong))
789 return std::max(ABIAlign, (unsigned)getTypeSize(T));
790
Chris Lattner34ebde42009-01-27 18:08:34 +0000791 return ABIAlign;
792}
793
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000794static void CollectLocalObjCIvars(ASTContext *Ctx,
795 const ObjCInterfaceDecl *OI,
796 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000797 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
798 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000799 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000800 if (!IVDecl->isInvalidDecl())
801 Fields.push_back(cast<FieldDecl>(IVDecl));
802 }
803}
804
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000805void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
806 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
807 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
808 CollectObjCIvars(SuperClass, Fields);
809 CollectLocalObjCIvars(this, OI, Fields);
810}
811
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000812/// ShallowCollectObjCIvars -
813/// Collect all ivars, including those synthesized, in the current class.
814///
815void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
816 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
817 bool CollectSynthesized) {
818 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
819 E = OI->ivar_end(); I != E; ++I) {
820 Ivars.push_back(*I);
821 }
822 if (CollectSynthesized)
823 CollectSynthesizedIvars(OI, Ivars);
824}
825
Fariborz Jahanian98200742009-05-12 18:14:29 +0000826void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
827 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000828 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
829 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000830 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
831 Ivars.push_back(Ivar);
832
833 // Also look into nested protocols.
834 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
835 E = PD->protocol_end(); P != E; ++P)
836 CollectProtocolSynthesizedIvars(*P, Ivars);
837}
838
839/// CollectSynthesizedIvars -
840/// This routine collect synthesized ivars for the designated class.
841///
842void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
843 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000844 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
845 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000846 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
847 Ivars.push_back(Ivar);
848 }
849 // Also look into interface's protocol list for properties declared
850 // in the protocol and whose ivars are synthesized.
851 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
852 PE = OI->protocol_end(); P != PE; ++P) {
853 ObjCProtocolDecl *PD = (*P);
854 CollectProtocolSynthesizedIvars(PD, Ivars);
855 }
856}
857
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000858unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
859 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000860 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
861 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000862 if ((*I)->getPropertyIvarDecl())
863 ++count;
864
865 // Also look into nested protocols.
866 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
867 E = PD->protocol_end(); P != E; ++P)
868 count += CountProtocolSynthesizedIvars(*P);
869 return count;
870}
871
872unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
873{
874 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000875 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
876 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000877 if ((*I)->getPropertyIvarDecl())
878 ++count;
879 }
880 // Also look into interface's protocol list for properties declared
881 // in the protocol and whose ivars are synthesized.
882 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
883 PE = OI->protocol_end(); P != PE; ++P) {
884 ObjCProtocolDecl *PD = (*P);
885 count += CountProtocolSynthesizedIvars(PD);
886 }
887 return count;
888}
889
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000890/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
891ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
892 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
893 I = ObjCImpls.find(D);
894 if (I != ObjCImpls.end())
895 return cast<ObjCImplementationDecl>(I->second);
896 return 0;
897}
898/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
899ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
901 I = ObjCImpls.find(D);
902 if (I != ObjCImpls.end())
903 return cast<ObjCCategoryImplDecl>(I->second);
904 return 0;
905}
906
907/// \brief Set the implementation of ObjCInterfaceDecl.
908void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
909 ObjCImplementationDecl *ImplD) {
910 assert(IFaceD && ImplD && "Passed null params");
911 ObjCImpls[IFaceD] = ImplD;
912}
913/// \brief Set the implementation of ObjCCategoryDecl.
914void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
915 ObjCCategoryImplDecl *ImplD) {
916 assert(CatD && ImplD && "Passed null params");
917 ObjCImpls[CatD] = ImplD;
918}
919
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000920/// \brief Allocate an uninitialized DeclaratorInfo.
921///
922/// The caller should initialize the memory held by DeclaratorInfo using
923/// the TypeLoc wrappers.
924///
925/// \param T the type that will be the basis for type source info. This type
926/// should refer to how the declarator was written in source code, not to
927/// what type semantic analysis resolved the declarator to.
928DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T) {
929 unsigned DataSize = TypeLoc::getFullDataSizeForType(T);
930 DeclaratorInfo *DInfo =
931 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
932 new (DInfo) DeclaratorInfo(T);
933 return DInfo;
934}
935
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000936/// getInterfaceLayoutImpl - Get or compute information about the
937/// layout of the given interface.
938///
939/// \param Impl - If given, also include the layout of the interface's
940/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000941const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000942ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
943 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000944 assert(!D->isForwardDecl() && "Invalid interface decl!");
945
Devang Patel44a3dde2008-06-04 21:54:36 +0000946 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000947 ObjCContainerDecl *Key =
948 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
949 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
950 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000951
Daniel Dunbar453addb2009-05-03 11:16:44 +0000952 // Add in synthesized ivar count if laying out an implementation.
953 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000954 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000955 unsigned SynthCount = CountSynthesizedIvars(D);
956 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000957 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000958 // entry. Note we can't cache this because we simply free all
959 // entries later; however we shouldn't look up implementations
960 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000961 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000962 return getObjCLayout(D, 0);
963 }
964
Anders Carlsson29445a02009-07-18 21:19:52 +0000965 const ASTRecordLayout *NewEntry =
966 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
967 ObjCLayouts[Key] = NewEntry;
968
Devang Patel44a3dde2008-06-04 21:54:36 +0000969 return *NewEntry;
970}
971
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000972const ASTRecordLayout &
973ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
974 return getObjCLayout(D, 0);
975}
976
977const ASTRecordLayout &
978ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
979 return getObjCLayout(D->getClassInterface(), D);
980}
981
Devang Patel88a981b2007-11-01 19:11:01 +0000982/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000983/// specified record (struct/union/class), which indicates its size and field
984/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000985const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000986 D = D->getDefinition(*this);
987 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000988
Chris Lattner464175b2007-07-18 17:52:12 +0000989 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +0000990 // Note that we can't save a reference to the entry because this function
991 // is recursive.
992 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000993 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000994
Anders Carlsson29445a02009-07-18 21:19:52 +0000995 const ASTRecordLayout *NewEntry =
996 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000997 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000998
Chris Lattner5d2a6302007-07-18 18:26:58 +0000999 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001000}
1001
Chris Lattnera7674d82007-07-13 22:13:22 +00001002//===----------------------------------------------------------------------===//
1003// Type creation/memoization methods
1004//===----------------------------------------------------------------------===//
1005
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001006QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001007 QualType CanT = getCanonicalType(T);
1008 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001009 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001010
1011 // If we are composing extended qualifiers together, merge together into one
1012 // ExtQualType node.
1013 unsigned CVRQuals = T.getCVRQualifiers();
1014 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1015 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001016
Chris Lattnerb7d25532009-02-18 22:53:11 +00001017 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1018 // If this type already has an address space specified, it cannot get
1019 // another one.
1020 assert(EQT->getAddressSpace() == 0 &&
1021 "Type cannot be in multiple addr spaces!");
1022 GCAttr = EQT->getObjCGCAttr();
1023 TypeNode = EQT->getBaseType();
1024 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001025
Chris Lattnerb7d25532009-02-18 22:53:11 +00001026 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001027 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001028 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001029 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001030 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001031 return QualType(EXTQy, CVRQuals);
1032
Christopher Lambebb97e92008-02-04 02:31:56 +00001033 // If the base type isn't canonical, this won't be a canonical type either,
1034 // so fill in the canonical type field.
1035 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001036 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001037 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001038
Chris Lattnerb7d25532009-02-18 22:53:11 +00001039 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001040 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001041 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001042 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001043 ExtQualType *New =
1044 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001045 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001046 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001047 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001048}
1049
Chris Lattnerb7d25532009-02-18 22:53:11 +00001050QualType ASTContext::getObjCGCQualType(QualType T,
1051 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001052 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001053 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001054 return T;
1055
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001056 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001057 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001058 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001059 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1060 return getPointerType(ResultType);
1061 }
1062 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001063 // If we are composing extended qualifiers together, merge together into one
1064 // ExtQualType node.
1065 unsigned CVRQuals = T.getCVRQualifiers();
1066 Type *TypeNode = T.getTypePtr();
1067 unsigned AddressSpace = 0;
1068
1069 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
Mike Stump24556362009-07-25 21:26:53 +00001070 // If this type already has an ObjCGC specified, it cannot get
Chris Lattnerb7d25532009-02-18 22:53:11 +00001071 // another one.
1072 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
Mike Stump24556362009-07-25 21:26:53 +00001073 "Type cannot have multiple ObjCGCs!");
Chris Lattnerb7d25532009-02-18 22:53:11 +00001074 AddressSpace = EQT->getAddressSpace();
1075 TypeNode = EQT->getBaseType();
1076 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001077
1078 // Check if we've already instantiated an gc qual'd type of this type.
1079 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001080 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001081 void *InsertPos = 0;
1082 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001083 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001084
1085 // If the base type isn't canonical, this won't be a canonical type either,
1086 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001087 // FIXME: Isn't this also not canonical if the base type is a array
1088 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001089 QualType Canonical;
1090 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001091 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001092
Chris Lattnerb7d25532009-02-18 22:53:11 +00001093 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001094 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1095 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1096 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001097 ExtQualType *New =
1098 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001099 ExtQualTypes.InsertNode(New, InsertPos);
1100 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001101 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001102}
Chris Lattnera7674d82007-07-13 22:13:22 +00001103
Mike Stump24556362009-07-25 21:26:53 +00001104QualType ASTContext::getNoReturnType(QualType T) {
Mike Stump6dcbc292009-07-25 23:24:03 +00001105 QualifierSet qs;
1106 qs.strip(T);
Mike Stump24556362009-07-25 21:26:53 +00001107 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001108 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001109 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001110 ResultType = getPointerType(ResultType);
1111 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1112 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001113 }
1114 if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001115 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001116 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001117 ResultType = getBlockPointerType(ResultType);
1118 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1119 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001120 }
1121 if (!T->isFunctionType())
1122 assert(0 && "can't noreturn qualify non-pointer to function or block type");
1123
Mike Stumpe24aea22009-07-27 22:25:19 +00001124 if (const FunctionNoProtoType *F = T->getAsFunctionNoProtoType()) {
Mike Stump24556362009-07-25 21:26:53 +00001125 return getFunctionNoProtoType(F->getResultType(), true);
1126 }
Mike Stumpe24aea22009-07-27 22:25:19 +00001127 const FunctionProtoType *F = T->getAsFunctionProtoType();
Mike Stump24556362009-07-25 21:26:53 +00001128 return getFunctionType(F->getResultType(), F->arg_type_begin(),
1129 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1130 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1131 F->getNumExceptions(), F->exception_begin(), true);
1132}
1133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134/// getComplexType - Return the uniqued reference to the type for a complex
1135/// number with the specified element type.
1136QualType ASTContext::getComplexType(QualType T) {
1137 // Unique pointers, to guarantee there is only one pointer of a particular
1138 // structure.
1139 llvm::FoldingSetNodeID ID;
1140 ComplexType::Profile(ID, T);
1141
1142 void *InsertPos = 0;
1143 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1144 return QualType(CT, 0);
1145
1146 // If the pointee type isn't canonical, this won't be a canonical type either,
1147 // so fill in the canonical type field.
1148 QualType Canonical;
1149 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001150 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001151
1152 // Get the new insert position for the node we care about.
1153 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001154 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 }
Steve Narofff83820b2009-01-27 22:08:43 +00001156 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 Types.push_back(New);
1158 ComplexTypes.InsertNode(New, InsertPos);
1159 return QualType(New, 0);
1160}
1161
Eli Friedmanf98aba32009-02-13 02:31:07 +00001162QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1163 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1164 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1165 FixedWidthIntType *&Entry = Map[Width];
1166 if (!Entry)
1167 Entry = new FixedWidthIntType(Width, Signed);
1168 return QualType(Entry, 0);
1169}
Reid Spencer5f016e22007-07-11 17:01:13 +00001170
1171/// getPointerType - Return the uniqued reference to the type for a pointer to
1172/// the specified type.
1173QualType ASTContext::getPointerType(QualType T) {
1174 // Unique pointers, to guarantee there is only one pointer of a particular
1175 // structure.
1176 llvm::FoldingSetNodeID ID;
1177 PointerType::Profile(ID, T);
1178
1179 void *InsertPos = 0;
1180 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1181 return QualType(PT, 0);
1182
1183 // If the pointee type isn't canonical, this won't be a canonical type either,
1184 // so fill in the canonical type field.
1185 QualType Canonical;
1186 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001187 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001188
1189 // Get the new insert position for the node we care about.
1190 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001191 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 }
Steve Narofff83820b2009-01-27 22:08:43 +00001193 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 Types.push_back(New);
1195 PointerTypes.InsertNode(New, InsertPos);
1196 return QualType(New, 0);
1197}
1198
Steve Naroff5618bd42008-08-27 16:04:49 +00001199/// getBlockPointerType - Return the uniqued reference to the type for
1200/// a pointer to the specified block.
1201QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001202 assert(T->isFunctionType() && "block of function types only");
1203 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001204 // structure.
1205 llvm::FoldingSetNodeID ID;
1206 BlockPointerType::Profile(ID, T);
1207
1208 void *InsertPos = 0;
1209 if (BlockPointerType *PT =
1210 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1211 return QualType(PT, 0);
1212
Steve Naroff296e8d52008-08-28 19:20:44 +00001213 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001214 // type either so fill in the canonical type field.
1215 QualType Canonical;
1216 if (!T->isCanonical()) {
1217 Canonical = getBlockPointerType(getCanonicalType(T));
1218
1219 // Get the new insert position for the node we care about.
1220 BlockPointerType *NewIP =
1221 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001222 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001223 }
Steve Narofff83820b2009-01-27 22:08:43 +00001224 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001225 Types.push_back(New);
1226 BlockPointerTypes.InsertNode(New, InsertPos);
1227 return QualType(New, 0);
1228}
1229
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001230/// getLValueReferenceType - Return the uniqued reference to the type for an
1231/// lvalue reference to the specified type.
1232QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // Unique pointers, to guarantee there is only one pointer of a particular
1234 // structure.
1235 llvm::FoldingSetNodeID ID;
1236 ReferenceType::Profile(ID, T);
1237
1238 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001239 if (LValueReferenceType *RT =
1240 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001242
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 // If the referencee type isn't canonical, this won't be a canonical type
1244 // either, so fill in the canonical type field.
1245 QualType Canonical;
1246 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001247 Canonical = getLValueReferenceType(getCanonicalType(T));
1248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001250 LValueReferenceType *NewIP =
1251 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001252 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 }
1254
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001255 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001257 LValueReferenceTypes.InsertNode(New, InsertPos);
1258 return QualType(New, 0);
1259}
1260
1261/// getRValueReferenceType - Return the uniqued reference to the type for an
1262/// rvalue reference to the specified type.
1263QualType ASTContext::getRValueReferenceType(QualType T) {
1264 // Unique pointers, to guarantee there is only one pointer of a particular
1265 // structure.
1266 llvm::FoldingSetNodeID ID;
1267 ReferenceType::Profile(ID, T);
1268
1269 void *InsertPos = 0;
1270 if (RValueReferenceType *RT =
1271 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1272 return QualType(RT, 0);
1273
1274 // If the referencee type isn't canonical, this won't be a canonical type
1275 // either, so fill in the canonical type field.
1276 QualType Canonical;
1277 if (!T->isCanonical()) {
1278 Canonical = getRValueReferenceType(getCanonicalType(T));
1279
1280 // Get the new insert position for the node we care about.
1281 RValueReferenceType *NewIP =
1282 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1283 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1284 }
1285
1286 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1287 Types.push_back(New);
1288 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 return QualType(New, 0);
1290}
1291
Sebastian Redlf30208a2009-01-24 21:16:55 +00001292/// getMemberPointerType - Return the uniqued reference to the type for a
1293/// member pointer to the specified type, in the specified class.
1294QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1295{
1296 // Unique pointers, to guarantee there is only one pointer of a particular
1297 // structure.
1298 llvm::FoldingSetNodeID ID;
1299 MemberPointerType::Profile(ID, T, Cls);
1300
1301 void *InsertPos = 0;
1302 if (MemberPointerType *PT =
1303 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1304 return QualType(PT, 0);
1305
1306 // If the pointee or class type isn't canonical, this won't be a canonical
1307 // type either, so fill in the canonical type field.
1308 QualType Canonical;
1309 if (!T->isCanonical()) {
1310 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1311
1312 // Get the new insert position for the node we care about.
1313 MemberPointerType *NewIP =
1314 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1315 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1316 }
Steve Narofff83820b2009-01-27 22:08:43 +00001317 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001318 Types.push_back(New);
1319 MemberPointerTypes.InsertNode(New, InsertPos);
1320 return QualType(New, 0);
1321}
1322
Steve Narofffb22d962007-08-30 01:06:46 +00001323/// getConstantArrayType - Return the unique reference to the type for an
1324/// array of the specified element type.
1325QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001326 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001327 ArrayType::ArraySizeModifier ASM,
1328 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001329 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1330 "Constant array of VLAs is illegal!");
1331
Chris Lattner38aeec72009-05-13 04:12:56 +00001332 // Convert the array size into a canonical width matching the pointer size for
1333 // the target.
1334 llvm::APInt ArySize(ArySizeIn);
1335 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001338 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001339
1340 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001341 if (ConstantArrayType *ATP =
1342 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 return QualType(ATP, 0);
1344
1345 // If the element type isn't canonical, this won't be a canonical type either,
1346 // so fill in the canonical type field.
1347 QualType Canonical;
1348 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001349 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001350 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001352 ConstantArrayType *NewIP =
1353 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001354 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 }
1356
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001357 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001358 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001359 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 Types.push_back(New);
1361 return QualType(New, 0);
1362}
1363
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001364/// getConstantArrayWithExprType - Return a reference to the type for
1365/// an array of the specified element type.
1366QualType
1367ASTContext::getConstantArrayWithExprType(QualType EltTy,
1368 const llvm::APInt &ArySizeIn,
1369 Expr *ArySizeExpr,
1370 ArrayType::ArraySizeModifier ASM,
1371 unsigned EltTypeQuals,
1372 SourceRange Brackets) {
1373 // Convert the array size into a canonical width matching the pointer
1374 // size for the target.
1375 llvm::APInt ArySize(ArySizeIn);
1376 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1377
1378 // Compute the canonical ConstantArrayType.
1379 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1380 ArySize, ASM, EltTypeQuals);
1381 // Since we don't unique expressions, it isn't possible to unique VLA's
1382 // that have an expression provided for their size.
1383 ConstantArrayWithExprType *New =
1384 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1385 ArySize, ArySizeExpr,
1386 ASM, EltTypeQuals, Brackets);
1387 Types.push_back(New);
1388 return QualType(New, 0);
1389}
1390
1391/// getConstantArrayWithoutExprType - Return a reference to the type for
1392/// an array of the specified element type.
1393QualType
1394ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1395 const llvm::APInt &ArySizeIn,
1396 ArrayType::ArraySizeModifier ASM,
1397 unsigned EltTypeQuals) {
1398 // Convert the array size into a canonical width matching the pointer
1399 // size for the target.
1400 llvm::APInt ArySize(ArySizeIn);
1401 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1402
1403 // Compute the canonical ConstantArrayType.
1404 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1405 ArySize, ASM, EltTypeQuals);
1406 ConstantArrayWithoutExprType *New =
1407 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1408 ArySize, ASM, EltTypeQuals);
1409 Types.push_back(New);
1410 return QualType(New, 0);
1411}
1412
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001413/// getVariableArrayType - Returns a non-unique reference to the type for a
1414/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001415QualType ASTContext::getVariableArrayType(QualType EltTy,
1416 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001417 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001418 unsigned EltTypeQuals,
1419 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001420 // Since we don't unique expressions, it isn't possible to unique VLA's
1421 // that have an expression provided for their size.
1422
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001423 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001424 new(*this,8)VariableArrayType(EltTy, QualType(),
1425 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001426
1427 VariableArrayTypes.push_back(New);
1428 Types.push_back(New);
1429 return QualType(New, 0);
1430}
1431
Douglas Gregor898574e2008-12-05 23:32:09 +00001432/// getDependentSizedArrayType - Returns a non-unique reference to
1433/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001434/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001435QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1436 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001437 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001438 unsigned EltTypeQuals,
1439 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001440 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1441 "Size must be type- or value-dependent!");
1442
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001443 llvm::FoldingSetNodeID ID;
1444 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1445 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001446
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001447 void *InsertPos = 0;
1448 DependentSizedArrayType *Canon
1449 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1450 DependentSizedArrayType *New;
1451 if (Canon) {
1452 // We already have a canonical version of this array type; use it as
1453 // the canonical type for a newly-built type.
1454 New = new (*this,8) DependentSizedArrayType(*this, EltTy,
1455 QualType(Canon, 0),
1456 NumElts, ASM, EltTypeQuals,
1457 Brackets);
1458 } else {
1459 QualType CanonEltTy = getCanonicalType(EltTy);
1460 if (CanonEltTy == EltTy) {
1461 New = new (*this,8) DependentSizedArrayType(*this, EltTy, QualType(),
1462 NumElts, ASM, EltTypeQuals,
1463 Brackets);
1464 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1465 } else {
1466 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1467 ASM, EltTypeQuals,
1468 SourceRange());
1469 New = new (*this,8) DependentSizedArrayType(*this, EltTy, Canon,
1470 NumElts, ASM, EltTypeQuals,
1471 Brackets);
1472 }
1473 }
1474
Douglas Gregor898574e2008-12-05 23:32:09 +00001475 Types.push_back(New);
1476 return QualType(New, 0);
1477}
1478
Eli Friedmanc5773c42008-02-15 18:16:39 +00001479QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1480 ArrayType::ArraySizeModifier ASM,
1481 unsigned EltTypeQuals) {
1482 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001483 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001484
1485 void *InsertPos = 0;
1486 if (IncompleteArrayType *ATP =
1487 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1488 return QualType(ATP, 0);
1489
1490 // If the element type isn't canonical, this won't be a canonical type
1491 // either, so fill in the canonical type field.
1492 QualType Canonical;
1493
1494 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001495 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001496 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001497
1498 // Get the new insert position for the node we care about.
1499 IncompleteArrayType *NewIP =
1500 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001501 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001502 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001503
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001504 IncompleteArrayType *New
1505 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1506 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001507
1508 IncompleteArrayTypes.InsertNode(New, InsertPos);
1509 Types.push_back(New);
1510 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001511}
1512
Steve Naroff73322922007-07-18 18:00:27 +00001513/// getVectorType - Return the unique reference to a vector type of
1514/// the specified element type and size. VectorType must be a built-in type.
1515QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 BuiltinType *baseType;
1517
Chris Lattnerf52ab252008-04-06 22:59:24 +00001518 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001519 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001520
1521 // Check if we've already instantiated a vector of this type.
1522 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001523 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 void *InsertPos = 0;
1525 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1526 return QualType(VTP, 0);
1527
1528 // If the element type isn't canonical, this won't be a canonical type either,
1529 // so fill in the canonical type field.
1530 QualType Canonical;
1531 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001532 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001533
1534 // Get the new insert position for the node we care about.
1535 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001536 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 }
Steve Narofff83820b2009-01-27 22:08:43 +00001538 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 VectorTypes.InsertNode(New, InsertPos);
1540 Types.push_back(New);
1541 return QualType(New, 0);
1542}
1543
Nate Begeman213541a2008-04-18 23:10:10 +00001544/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001545/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001546QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001547 BuiltinType *baseType;
1548
Chris Lattnerf52ab252008-04-06 22:59:24 +00001549 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001550 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001551
1552 // Check if we've already instantiated a vector of this type.
1553 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001554 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001555 void *InsertPos = 0;
1556 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1557 return QualType(VTP, 0);
1558
1559 // If the element type isn't canonical, this won't be a canonical type either,
1560 // so fill in the canonical type field.
1561 QualType Canonical;
1562 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001563 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001564
1565 // Get the new insert position for the node we care about.
1566 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001567 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001568 }
Steve Narofff83820b2009-01-27 22:08:43 +00001569 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001570 VectorTypes.InsertNode(New, InsertPos);
1571 Types.push_back(New);
1572 return QualType(New, 0);
1573}
1574
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001575QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1576 Expr *SizeExpr,
1577 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001578 llvm::FoldingSetNodeID ID;
1579 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1580 SizeExpr);
1581
1582 void *InsertPos = 0;
1583 DependentSizedExtVectorType *Canon
1584 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1585 DependentSizedExtVectorType *New;
1586 if (Canon) {
1587 // We already have a canonical version of this array type; use it as
1588 // the canonical type for a newly-built type.
1589 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1590 QualType(Canon, 0),
1591 SizeExpr, AttrLoc);
1592 } else {
1593 QualType CanonVecTy = getCanonicalType(vecType);
1594 if (CanonVecTy == vecType) {
1595 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1596 QualType(), SizeExpr,
1597 AttrLoc);
1598 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1599 } else {
1600 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1601 SourceLocation());
1602 New = new (*this,8) DependentSizedExtVectorType(*this, vecType, Canon,
1603 SizeExpr, AttrLoc);
1604 }
1605 }
1606
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001607 Types.push_back(New);
1608 return QualType(New, 0);
1609}
1610
Douglas Gregor72564e72009-02-26 23:50:07 +00001611/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001612///
Mike Stump24556362009-07-25 21:26:53 +00001613QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 // Unique functions, to guarantee there is only one function of a particular
1615 // structure.
1616 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001617 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001618
1619 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001620 if (FunctionNoProtoType *FT =
1621 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 return QualType(FT, 0);
1623
1624 QualType Canonical;
1625 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001626 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001627
1628 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001629 FunctionNoProtoType *NewIP =
1630 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001631 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 }
1633
Mike Stump24556362009-07-25 21:26:53 +00001634 FunctionNoProtoType *New
1635 = new (*this,8) FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001637 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 return QualType(New, 0);
1639}
1640
1641/// getFunctionType - Return a normal function type with a typed argument
1642/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001643QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001644 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001645 unsigned TypeQuals, bool hasExceptionSpec,
1646 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001647 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 // Unique functions, to guarantee there is only one function of a particular
1649 // structure.
1650 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001651 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001652 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001653 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001654
1655 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001656 if (FunctionProtoType *FTP =
1657 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001659
1660 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001662 if (hasExceptionSpec)
1663 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1665 if (!ArgArray[i]->isCanonical())
1666 isCanonical = false;
1667
1668 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001669 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 QualType Canonical;
1671 if (!isCanonical) {
1672 llvm::SmallVector<QualType, 16> CanonicalArgs;
1673 CanonicalArgs.reserve(NumArgs);
1674 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001675 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001676
Chris Lattnerf52ab252008-04-06 22:59:24 +00001677 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001678 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001679 isVariadic, TypeQuals, false,
1680 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001681
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001683 FunctionProtoType *NewIP =
1684 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001685 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001687
Douglas Gregor72564e72009-02-26 23:50:07 +00001688 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001689 // for two variable size arrays (for parameter and exception types) at the
1690 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001691 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001692 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1693 NumArgs*sizeof(QualType) +
1694 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001696 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001697 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001699 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 return QualType(FTP, 0);
1701}
1702
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001703/// getTypeDeclType - Return the unique reference to the type for the
1704/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001705QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001706 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001707 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1708
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001709 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001710 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001711 else if (isa<TemplateTypeParmDecl>(Decl)) {
1712 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001713 } else if (ObjCInterfaceDecl *ObjCInterface
1714 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001715 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001716
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001717 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001718 if (PrevDecl)
1719 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001720 else
1721 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001722 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001723 if (PrevDecl)
1724 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001725 else
1726 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001727 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001728 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001729
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001730 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001731 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001732}
1733
Reid Spencer5f016e22007-07-11 17:01:13 +00001734/// getTypedefType - Return the unique reference to the type for the
1735/// specified typename decl.
1736QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1737 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1738
Chris Lattnerf52ab252008-04-06 22:59:24 +00001739 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001740 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 Types.push_back(Decl->TypeForDecl);
1742 return QualType(Decl->TypeForDecl, 0);
1743}
1744
Douglas Gregorfab9d672009-02-05 23:33:38 +00001745/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001746/// parameter or parameter pack with the given depth, index, and (optionally)
1747/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001748QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001749 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001750 IdentifierInfo *Name) {
1751 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001752 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001753 void *InsertPos = 0;
1754 TemplateTypeParmType *TypeParm
1755 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1756
1757 if (TypeParm)
1758 return QualType(TypeParm, 0);
1759
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001760 if (Name) {
1761 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1762 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1763 Name, Canon);
1764 } else
1765 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001766
1767 Types.push_back(TypeParm);
1768 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1769
1770 return QualType(TypeParm, 0);
1771}
1772
Douglas Gregor55f6b142009-02-09 18:46:07 +00001773QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001774ASTContext::getTemplateSpecializationType(TemplateName Template,
1775 const TemplateArgument *Args,
1776 unsigned NumArgs,
1777 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001778 if (!Canon.isNull())
1779 Canon = getCanonicalType(Canon);
1780 else {
1781 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001782 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1783 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1784 CanonArgs.reserve(NumArgs);
1785 for (unsigned I = 0; I != NumArgs; ++I)
1786 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1787
1788 // Determine whether this canonical template specialization type already
1789 // exists.
1790 llvm::FoldingSetNodeID ID;
1791 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001792 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001793
1794 void *InsertPos = 0;
1795 TemplateSpecializationType *Spec
1796 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1797
1798 if (!Spec) {
1799 // Allocate a new canonical template specialization type.
1800 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1801 sizeof(TemplateArgument) * NumArgs),
1802 8);
Douglas Gregor828e2262009-07-29 16:09:57 +00001803 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001804 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001805 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001806 Types.push_back(Spec);
1807 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1808 }
1809
Douglas Gregorb88e8882009-07-30 17:40:51 +00001810 if (Canon.isNull())
1811 Canon = QualType(Spec, 0);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001812 assert(Canon->isDependentType() &&
1813 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001814 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001815
Douglas Gregor1275ae02009-07-28 23:00:59 +00001816 // Allocate the (non-canonical) template specialization type, but don't
1817 // try to unique it: these types typically have location information that
1818 // we don't unique and don't want to lose.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001819 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001820 sizeof(TemplateArgument) * NumArgs),
1821 8);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001822 TemplateSpecializationType *Spec
Douglas Gregor828e2262009-07-29 16:09:57 +00001823 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1824 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001825
Douglas Gregor55f6b142009-02-09 18:46:07 +00001826 Types.push_back(Spec);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001827 return QualType(Spec, 0);
1828}
1829
Douglas Gregore4e5b052009-03-19 00:18:19 +00001830QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001831ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001832 QualType NamedType) {
1833 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001834 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001835
1836 void *InsertPos = 0;
1837 QualifiedNameType *T
1838 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1839 if (T)
1840 return QualType(T, 0);
1841
Douglas Gregorab452ba2009-03-26 23:50:42 +00001842 T = new (*this) QualifiedNameType(NNS, NamedType,
1843 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001844 Types.push_back(T);
1845 QualifiedNameTypes.InsertNode(T, InsertPos);
1846 return QualType(T, 0);
1847}
1848
Douglas Gregord57959a2009-03-27 23:10:48 +00001849QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1850 const IdentifierInfo *Name,
1851 QualType Canon) {
1852 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1853
1854 if (Canon.isNull()) {
1855 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1856 if (CanonNNS != NNS)
1857 Canon = getTypenameType(CanonNNS, Name);
1858 }
1859
1860 llvm::FoldingSetNodeID ID;
1861 TypenameType::Profile(ID, NNS, Name);
1862
1863 void *InsertPos = 0;
1864 TypenameType *T
1865 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1866 if (T)
1867 return QualType(T, 0);
1868
1869 T = new (*this) TypenameType(NNS, Name, Canon);
1870 Types.push_back(T);
1871 TypenameTypes.InsertNode(T, InsertPos);
1872 return QualType(T, 0);
1873}
1874
Douglas Gregor17343172009-04-01 00:28:59 +00001875QualType
1876ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1877 const TemplateSpecializationType *TemplateId,
1878 QualType Canon) {
1879 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1880
1881 if (Canon.isNull()) {
1882 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1883 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1884 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1885 const TemplateSpecializationType *CanonTemplateId
1886 = CanonType->getAsTemplateSpecializationType();
1887 assert(CanonTemplateId &&
1888 "Canonical type must also be a template specialization type");
1889 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1890 }
1891 }
1892
1893 llvm::FoldingSetNodeID ID;
1894 TypenameType::Profile(ID, NNS, TemplateId);
1895
1896 void *InsertPos = 0;
1897 TypenameType *T
1898 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1899 if (T)
1900 return QualType(T, 0);
1901
1902 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1903 Types.push_back(T);
1904 TypenameTypes.InsertNode(T, InsertPos);
1905 return QualType(T, 0);
1906}
1907
John McCall7da24312009-09-05 00:15:47 +00001908QualType
1909ASTContext::getElaboratedType(QualType UnderlyingType,
1910 ElaboratedType::TagKind Tag) {
1911 llvm::FoldingSetNodeID ID;
1912 ElaboratedType::Profile(ID, UnderlyingType, Tag);
1913
1914 void *InsertPos = 0;
1915 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1916 if (T)
1917 return QualType(T, 0);
1918
1919 QualType Canon = getCanonicalType(UnderlyingType);
1920
1921 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1922 Types.push_back(T);
1923 ElaboratedTypes.InsertNode(T, InsertPos);
1924 return QualType(T, 0);
1925}
1926
Chris Lattner88cb27a2008-04-07 04:56:42 +00001927/// CmpProtocolNames - Comparison predicate for sorting protocols
1928/// alphabetically.
1929static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1930 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001931 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001932}
1933
1934static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1935 unsigned &NumProtocols) {
1936 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1937
1938 // Sort protocols, keyed by name.
1939 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1940
1941 // Remove duplicates.
1942 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1943 NumProtocols = ProtocolsEnd-Protocols;
1944}
1945
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001946/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1947/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001948QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001949 ObjCProtocolDecl **Protocols,
1950 unsigned NumProtocols) {
1951 // Sort the protocol list alphabetically to canonicalize it.
1952 if (NumProtocols)
1953 SortAndUniqueProtocols(Protocols, NumProtocols);
1954
1955 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001956 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001957
1958 void *InsertPos = 0;
1959 if (ObjCObjectPointerType *QT =
1960 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1961 return QualType(QT, 0);
1962
1963 // No Match;
1964 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001965 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001966
1967 Types.push_back(QType);
1968 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1969 return QualType(QType, 0);
1970}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001971
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001972/// getObjCInterfaceType - Return the unique reference to the type for the
1973/// specified ObjC interface decl. The list of protocols is optional.
1974QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001975 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001976 if (NumProtocols)
1977 // Sort the protocol list alphabetically to canonicalize it.
1978 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001979
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001980 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001981 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001982
1983 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001984 if (ObjCInterfaceType *QT =
1985 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001986 return QualType(QT, 0);
1987
1988 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001989 ObjCInterfaceType *QType =
1990 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1991 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001992 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001993 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001994 return QualType(QType, 0);
1995}
1996
Douglas Gregor72564e72009-02-26 23:50:07 +00001997/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1998/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001999/// multiple declarations that refer to "typeof(x)" all contain different
2000/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2001/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002002QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002003 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002004 if (tofExpr->isTypeDependent()) {
2005 llvm::FoldingSetNodeID ID;
2006 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2007
2008 void *InsertPos = 0;
2009 DependentTypeOfExprType *Canon
2010 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2011 if (Canon) {
2012 // We already have a "canonical" version of an identical, dependent
2013 // typeof(expr) type. Use that as our canonical type.
2014 toe = new (*this, 8) TypeOfExprType(tofExpr,
2015 QualType((TypeOfExprType*)Canon, 0));
2016 }
2017 else {
2018 // Build a new, canonical typeof(expr) type.
2019 Canon = new (*this, 8) DependentTypeOfExprType(*this, tofExpr);
2020 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2021 toe = Canon;
2022 }
2023 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002024 QualType Canonical = getCanonicalType(tofExpr->getType());
2025 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
2026 }
Steve Naroff9752f252007-08-01 18:02:17 +00002027 Types.push_back(toe);
2028 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002029}
2030
Steve Naroff9752f252007-08-01 18:02:17 +00002031/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2032/// TypeOfType AST's. The only motivation to unique these nodes would be
2033/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2034/// an issue. This doesn't effect the type checker, since it operates
2035/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002036QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002037 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00002038 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002039 Types.push_back(tot);
2040 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002041}
2042
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002043/// getDecltypeForExpr - Given an expr, will return the decltype for that
2044/// expression, according to the rules in C++0x [dcl.type.simple]p4
2045static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002046 if (e->isTypeDependent())
2047 return Context.DependentTy;
2048
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002049 // If e is an id expression or a class member access, decltype(e) is defined
2050 // as the type of the entity named by e.
2051 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2052 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2053 return VD->getType();
2054 }
2055 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2056 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2057 return FD->getType();
2058 }
2059 // If e is a function call or an invocation of an overloaded operator,
2060 // (parentheses around e are ignored), decltype(e) is defined as the
2061 // return type of that function.
2062 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2063 return CE->getCallReturnType();
2064
2065 QualType T = e->getType();
2066
2067 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2068 // defined as T&, otherwise decltype(e) is defined as T.
2069 if (e->isLvalue(Context) == Expr::LV_Valid)
2070 T = Context.getLValueReferenceType(T);
2071
2072 return T;
2073}
2074
Anders Carlsson395b4752009-06-24 19:06:50 +00002075/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2076/// DecltypeType AST's. The only motivation to unique these nodes would be
2077/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2078/// an issue. This doesn't effect the type checker, since it operates
2079/// on canonical type's (which are always unique).
2080QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002081 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002082 if (e->isTypeDependent()) {
2083 llvm::FoldingSetNodeID ID;
2084 DependentDecltypeType::Profile(ID, *this, e);
2085
2086 void *InsertPos = 0;
2087 DependentDecltypeType *Canon
2088 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2089 if (Canon) {
2090 // We already have a "canonical" version of an equivalent, dependent
2091 // decltype type. Use that as our canonical type.
2092 dt = new (*this, 8) DecltypeType(e, DependentTy,
2093 QualType((DecltypeType*)Canon, 0));
2094 }
2095 else {
2096 // Build a new, canonical typeof(expr) type.
2097 Canon = new (*this, 8) DependentDecltypeType(*this, e);
2098 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2099 dt = Canon;
2100 }
2101 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002102 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00002103 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002104 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002105 Types.push_back(dt);
2106 return QualType(dt, 0);
2107}
2108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109/// getTagDeclType - Return the unique reference to the type for the
2110/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002111QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002112 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002113 // FIXME: What is the design on getTagDeclType when it requires casting
2114 // away const? mutable?
2115 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002116}
2117
2118/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2119/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2120/// needs to agree with the definition in <stddef.h>.
2121QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002122 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002123}
2124
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002125/// getSignedWCharType - Return the type of "signed wchar_t".
2126/// Used when in C++, as a GCC extension.
2127QualType ASTContext::getSignedWCharType() const {
2128 // FIXME: derive from "Target" ?
2129 return WCharTy;
2130}
2131
2132/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2133/// Used when in C++, as a GCC extension.
2134QualType ASTContext::getUnsignedWCharType() const {
2135 // FIXME: derive from "Target" ?
2136 return UnsignedIntTy;
2137}
2138
Chris Lattner8b9023b2007-07-13 03:05:23 +00002139/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2140/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2141QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002142 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002143}
2144
Chris Lattnere6327742008-04-02 05:18:44 +00002145//===----------------------------------------------------------------------===//
2146// Type Operators
2147//===----------------------------------------------------------------------===//
2148
Chris Lattner77c96472008-04-06 22:41:35 +00002149/// getCanonicalType - Return the canonical (structural) type corresponding to
2150/// the specified potentially non-canonical type. The non-canonical version
2151/// of a type may have many "decorated" versions of types. Decorators can
2152/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2153/// to be free of any of these, allowing two canonical types to be compared
2154/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002155CanQualType ASTContext::getCanonicalType(QualType T) {
Chris Lattner77c96472008-04-06 22:41:35 +00002156 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002157
2158 // If the result has type qualifiers, make sure to canonicalize them as well.
2159 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
Douglas Gregor50d62d12009-08-05 05:36:45 +00002160 if (TypeQuals == 0)
2161 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002162
2163 // If the type qualifiers are on an array type, get the canonical type of the
2164 // array with the qualifiers applied to the element type.
2165 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2166 if (!AT)
Douglas Gregor50d62d12009-08-05 05:36:45 +00002167 return CanQualType::CreateUnsafe(CanType.getQualifiedType(TypeQuals));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002168
2169 // Get the canonical version of the element with the extra qualifiers on it.
2170 // This can recursively sink qualifiers through multiple levels of arrays.
2171 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2172 NewEltTy = getCanonicalType(NewEltTy);
2173
2174 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002175 return CanQualType::CreateUnsafe(
2176 getConstantArrayType(NewEltTy, CAT->getSize(),
2177 CAT->getSizeModifier(),
2178 CAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002179 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002180 return CanQualType::CreateUnsafe(
2181 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2182 IAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002183
Douglas Gregor898574e2008-12-05 23:32:09 +00002184 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002185 return CanQualType::CreateUnsafe(
2186 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002187 DSAT->getSizeExpr() ?
2188 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002189 DSAT->getSizeModifier(),
2190 DSAT->getIndexTypeQualifier(),
2191 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002192
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002193 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002194 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002195 VAT->getSizeExpr() ?
2196 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002197 VAT->getSizeModifier(),
2198 VAT->getIndexTypeQualifier(),
2199 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002200}
2201
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002202TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2203 // If this template name refers to a template, the canonical
2204 // template name merely stores the template itself.
2205 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002206 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002207
Douglas Gregord99cbe62009-07-29 18:26:50 +00002208 // If this template name refers to a set of overloaded function templates,
2209 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002210 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2211 OverloadedFunctionDecl *CanonOvl = 0;
2212 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2213 FEnd = Ovl->function_end();
2214 F != FEnd; ++F) {
2215 Decl *Canon = F->get()->getCanonicalDecl();
2216 if (CanonOvl || Canon != F->get()) {
2217 if (!CanonOvl)
2218 CanonOvl = OverloadedFunctionDecl::Create(*this,
2219 Ovl->getDeclContext(),
2220 Ovl->getDeclName());
2221
2222 CanonOvl->addOverload(
2223 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2224 }
2225 }
2226
2227 return TemplateName(CanonOvl? CanonOvl : Ovl);
2228 }
Douglas Gregord99cbe62009-07-29 18:26:50 +00002229
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002230 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2231 assert(DTN && "Non-dependent template names must refer to template decls.");
2232 return DTN->CanonicalTemplateName;
2233}
2234
Douglas Gregor1275ae02009-07-28 23:00:59 +00002235TemplateArgument
2236ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2237 switch (Arg.getKind()) {
2238 case TemplateArgument::Null:
2239 return Arg;
2240
2241 case TemplateArgument::Expression:
2242 // FIXME: Build canonical expression?
2243 return Arg;
2244
2245 case TemplateArgument::Declaration:
2246 return TemplateArgument(SourceLocation(),
2247 Arg.getAsDecl()->getCanonicalDecl());
2248
2249 case TemplateArgument::Integral:
2250 return TemplateArgument(SourceLocation(),
2251 *Arg.getAsIntegral(),
2252 getCanonicalType(Arg.getIntegralType()));
2253
2254 case TemplateArgument::Type:
2255 return TemplateArgument(SourceLocation(),
2256 getCanonicalType(Arg.getAsType()));
2257
2258 case TemplateArgument::Pack: {
2259 // FIXME: Allocate in ASTContext
2260 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2261 unsigned Idx = 0;
2262 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2263 AEnd = Arg.pack_end();
2264 A != AEnd; (void)++A, ++Idx)
2265 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2266
2267 TemplateArgument Result;
2268 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2269 return Result;
2270 }
2271 }
2272
2273 // Silence GCC warning
2274 assert(false && "Unhandled template argument kind");
2275 return TemplateArgument();
2276}
2277
Douglas Gregord57959a2009-03-27 23:10:48 +00002278NestedNameSpecifier *
2279ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2280 if (!NNS)
2281 return 0;
2282
2283 switch (NNS->getKind()) {
2284 case NestedNameSpecifier::Identifier:
2285 // Canonicalize the prefix but keep the identifier the same.
2286 return NestedNameSpecifier::Create(*this,
2287 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2288 NNS->getAsIdentifier());
2289
2290 case NestedNameSpecifier::Namespace:
2291 // A namespace is canonical; build a nested-name-specifier with
2292 // this namespace and no prefix.
2293 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2294
2295 case NestedNameSpecifier::TypeSpec:
2296 case NestedNameSpecifier::TypeSpecWithTemplate: {
2297 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor495c35d2009-08-25 22:51:20 +00002298 return NestedNameSpecifier::Create(*this, 0,
Douglas Gregord57959a2009-03-27 23:10:48 +00002299 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2300 T.getTypePtr());
2301 }
2302
2303 case NestedNameSpecifier::Global:
2304 // The global specifier is canonical and unique.
2305 return NNS;
2306 }
2307
2308 // Required to silence a GCC warning
2309 return 0;
2310}
2311
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002312
2313const ArrayType *ASTContext::getAsArrayType(QualType T) {
2314 // Handle the non-qualified case efficiently.
2315 if (T.getCVRQualifiers() == 0) {
2316 // Handle the common positive case fast.
2317 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2318 return AT;
2319 }
2320
2321 // Handle the common negative case fast, ignoring CVR qualifiers.
2322 QualType CType = T->getCanonicalTypeInternal();
2323
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002324 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002325 // test.
2326 if (!isa<ArrayType>(CType) &&
2327 !isa<ArrayType>(CType.getUnqualifiedType()))
2328 return 0;
2329
2330 // Apply any CVR qualifiers from the array type to the element type. This
2331 // implements C99 6.7.3p8: "If the specification of an array type includes
2332 // any type qualifiers, the element type is so qualified, not the array type."
2333
2334 // If we get here, we either have type qualifiers on the type, or we have
2335 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002336 // we must propagate them down into the element type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002337 unsigned CVRQuals = T.getCVRQualifiers();
2338 unsigned AddrSpace = 0;
2339 Type *Ty = T.getTypePtr();
2340
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002341 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002342 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002343 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2344 AddrSpace = EXTQT->getAddressSpace();
2345 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002346 } else {
2347 T = Ty->getDesugaredType();
2348 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2349 break;
2350 CVRQuals |= T.getCVRQualifiers();
2351 Ty = T.getTypePtr();
2352 }
2353 }
2354
2355 // If we have a simple case, just return now.
2356 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2357 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2358 return ATy;
2359
2360 // Otherwise, we have an array and we have qualifiers on it. Push the
2361 // qualifiers into the array element type and return a new array type.
2362 // Get the canonical version of the element with the extra qualifiers on it.
2363 // This can recursively sink qualifiers through multiple levels of arrays.
2364 QualType NewEltTy = ATy->getElementType();
2365 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002366 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002367 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2368
2369 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2370 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2371 CAT->getSizeModifier(),
2372 CAT->getIndexTypeQualifier()));
2373 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2374 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2375 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002376 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002377
Douglas Gregor898574e2008-12-05 23:32:09 +00002378 if (const DependentSizedArrayType *DSAT
2379 = dyn_cast<DependentSizedArrayType>(ATy))
2380 return cast<ArrayType>(
2381 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002382 DSAT->getSizeExpr() ?
2383 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002384 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002385 DSAT->getIndexTypeQualifier(),
2386 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002387
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002388 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002389 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002390 VAT->getSizeExpr() ?
2391 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002392 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002393 VAT->getIndexTypeQualifier(),
2394 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002395}
2396
2397
Chris Lattnere6327742008-04-02 05:18:44 +00002398/// getArrayDecayedType - Return the properly qualified result of decaying the
2399/// specified array type to a pointer. This operation is non-trivial when
2400/// handling typedefs etc. The canonical type of "T" must be an array type,
2401/// this returns a pointer to a properly qualified element of the array.
2402///
2403/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2404QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002405 // Get the element type with 'getAsArrayType' so that we don't lose any
2406 // typedefs in the element type of the array. This also handles propagation
2407 // of type qualifiers from the array type into the element type if present
2408 // (C99 6.7.3p8).
2409 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2410 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002411
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002412 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002413
2414 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002415 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002416}
2417
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002418QualType ASTContext::getBaseElementType(QualType QT) {
2419 QualifierSet qualifiers;
2420 while (true) {
2421 const Type *UT = qualifiers.strip(QT);
2422 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2423 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002424 } else {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002425 return qualifiers.apply(QT, *this);
2426 }
2427 }
2428}
2429
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002430QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002431 QualType ElemTy = VAT->getElementType();
2432
2433 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2434 return getBaseElementType(VAT);
2435
2436 return ElemTy;
2437}
2438
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002439/// getConstantArrayElementCount - Returns number of constant array elements.
2440uint64_t
2441ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2442 uint64_t ElementCount = 1;
2443 do {
2444 ElementCount *= CA->getSize().getZExtValue();
2445 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2446 } while (CA);
2447 return ElementCount;
2448}
2449
Reid Spencer5f016e22007-07-11 17:01:13 +00002450/// getFloatingRank - Return a relative rank for floating point types.
2451/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002452static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002453 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002454 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002455
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002456 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002457 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002458 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 case BuiltinType::Float: return FloatRank;
2460 case BuiltinType::Double: return DoubleRank;
2461 case BuiltinType::LongDouble: return LongDoubleRank;
2462 }
2463}
2464
Steve Naroff716c7302007-08-27 01:41:48 +00002465/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2466/// point or a complex type (based on typeDomain/typeSize).
2467/// 'typeDomain' is a real floating point or complex type.
2468/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002469QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2470 QualType Domain) const {
2471 FloatingRank EltRank = getFloatingRank(Size);
2472 if (Domain->isComplexType()) {
2473 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002474 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002475 case FloatRank: return FloatComplexTy;
2476 case DoubleRank: return DoubleComplexTy;
2477 case LongDoubleRank: return LongDoubleComplexTy;
2478 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 }
Chris Lattner1361b112008-04-06 23:58:54 +00002480
2481 assert(Domain->isRealFloatingType() && "Unknown domain!");
2482 switch (EltRank) {
2483 default: assert(0 && "getFloatingRank(): illegal value for rank");
2484 case FloatRank: return FloatTy;
2485 case DoubleRank: return DoubleTy;
2486 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002487 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002488}
2489
Chris Lattner7cfeb082008-04-06 23:55:33 +00002490/// getFloatingTypeOrder - Compare the rank of the two specified floating
2491/// point types, ignoring the domain of the type (i.e. 'double' ==
2492/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2493/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002494int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2495 FloatingRank LHSR = getFloatingRank(LHS);
2496 FloatingRank RHSR = getFloatingRank(RHS);
2497
2498 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002499 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002500 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002501 return 1;
2502 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002503}
2504
Chris Lattnerf52ab252008-04-06 22:59:24 +00002505/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2506/// routine will assert if passed a built-in type that isn't an integer or enum,
2507/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002508unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002509 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002510 if (EnumType* ET = dyn_cast<EnumType>(T))
2511 T = ET->getDecl()->getIntegerType().getTypePtr();
2512
Eli Friedmana3426752009-07-05 23:44:27 +00002513 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2514 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2515
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002516 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2517 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2518
2519 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2520 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2521
Eli Friedmanf98aba32009-02-13 02:31:07 +00002522 // There are two things which impact the integer rank: the width, and
2523 // the ordering of builtins. The builtin ordering is encoded in the
2524 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002525 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002526 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002527
Chris Lattnerf52ab252008-04-06 22:59:24 +00002528 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002529 default: assert(0 && "getIntegerRank(): not a built-in integer");
2530 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002531 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002532 case BuiltinType::Char_S:
2533 case BuiltinType::Char_U:
2534 case BuiltinType::SChar:
2535 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002536 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002537 case BuiltinType::Short:
2538 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002539 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002540 case BuiltinType::Int:
2541 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002542 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002543 case BuiltinType::Long:
2544 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002545 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002546 case BuiltinType::LongLong:
2547 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002548 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002549 case BuiltinType::Int128:
2550 case BuiltinType::UInt128:
2551 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002552 }
2553}
2554
Eli Friedman04e83572009-08-20 04:21:42 +00002555/// \brief Whether this is a promotable bitfield reference according
2556/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2557///
2558/// \returns the type this bit-field will promote to, or NULL if no
2559/// promotion occurs.
2560QualType ASTContext::isPromotableBitField(Expr *E) {
2561 FieldDecl *Field = E->getBitField();
2562 if (!Field)
2563 return QualType();
2564
2565 QualType FT = Field->getType();
2566
2567 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2568 uint64_t BitWidth = BitWidthAP.getZExtValue();
2569 uint64_t IntSize = getTypeSize(IntTy);
2570 // GCC extension compatibility: if the bit-field size is less than or equal
2571 // to the size of int, it gets promoted no matter what its type is.
2572 // For instance, unsigned long bf : 4 gets promoted to signed int.
2573 if (BitWidth < IntSize)
2574 return IntTy;
2575
2576 if (BitWidth == IntSize)
2577 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2578
2579 // Types bigger than int are not subject to promotions, and therefore act
2580 // like the base type.
2581 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2582 // is ridiculous.
2583 return QualType();
2584}
2585
Eli Friedmana95d7572009-08-19 07:44:53 +00002586/// getPromotedIntegerType - Returns the type that Promotable will
2587/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2588/// integer type.
2589QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2590 assert(!Promotable.isNull());
2591 assert(Promotable->isPromotableIntegerType());
2592 if (Promotable->isSignedIntegerType())
2593 return IntTy;
2594 uint64_t PromotableSize = getTypeSize(Promotable);
2595 uint64_t IntSize = getTypeSize(IntTy);
2596 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2597 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2598}
2599
Chris Lattner7cfeb082008-04-06 23:55:33 +00002600/// getIntegerTypeOrder - Returns the highest ranked integer type:
2601/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2602/// LHS < RHS, return -1.
2603int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002604 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2605 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002606 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002607
Chris Lattnerf52ab252008-04-06 22:59:24 +00002608 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2609 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002610
Chris Lattner7cfeb082008-04-06 23:55:33 +00002611 unsigned LHSRank = getIntegerRank(LHSC);
2612 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002613
Chris Lattner7cfeb082008-04-06 23:55:33 +00002614 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2615 if (LHSRank == RHSRank) return 0;
2616 return LHSRank > RHSRank ? 1 : -1;
2617 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002618
Chris Lattner7cfeb082008-04-06 23:55:33 +00002619 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2620 if (LHSUnsigned) {
2621 // If the unsigned [LHS] type is larger, return it.
2622 if (LHSRank >= RHSRank)
2623 return 1;
2624
2625 // If the signed type can represent all values of the unsigned type, it
2626 // wins. Because we are dealing with 2's complement and types that are
2627 // powers of two larger than each other, this is always safe.
2628 return -1;
2629 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002630
Chris Lattner7cfeb082008-04-06 23:55:33 +00002631 // If the unsigned [RHS] type is larger, return it.
2632 if (RHSRank >= LHSRank)
2633 return -1;
2634
2635 // If the signed type can represent all values of the unsigned type, it
2636 // wins. Because we are dealing with 2's complement and types that are
2637 // powers of two larger than each other, this is always safe.
2638 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002639}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002640
2641// getCFConstantStringType - Return the type used for constant CFStrings.
2642QualType ASTContext::getCFConstantStringType() {
2643 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002644 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002645 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002646 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002647 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002648
2649 // const int *isa;
2650 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002651 // int flags;
2652 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002653 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002654 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002655 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002656 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002657
Anders Carlsson71993dd2007-08-17 05:31:46 +00002658 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002659 for (unsigned i = 0; i < 4; ++i) {
2660 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2661 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002662 FieldTypes[i], /*DInfo=*/0,
2663 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002664 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002665 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002666 }
2667
2668 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002669 }
2670
2671 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002672}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002673
Douglas Gregor319ac892009-04-23 22:29:11 +00002674void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002675 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002676 assert(Rec && "Invalid CFConstantStringType");
2677 CFConstantStringTypeDecl = Rec->getDecl();
2678}
2679
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002680QualType ASTContext::getObjCFastEnumerationStateType()
2681{
2682 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002683 ObjCFastEnumerationStateTypeDecl =
2684 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2685 &Idents.get("__objcFastEnumerationState"));
2686
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002687 QualType FieldTypes[] = {
2688 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002689 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002690 getPointerType(UnsignedLongTy),
2691 getConstantArrayType(UnsignedLongTy,
2692 llvm::APInt(32, 5), ArrayType::Normal, 0)
2693 };
2694
Douglas Gregor44b43212008-12-11 16:49:14 +00002695 for (size_t i = 0; i < 4; ++i) {
2696 FieldDecl *Field = FieldDecl::Create(*this,
2697 ObjCFastEnumerationStateTypeDecl,
2698 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002699 FieldTypes[i], /*DInfo=*/0,
2700 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002701 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002702 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002703 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002704
Douglas Gregor44b43212008-12-11 16:49:14 +00002705 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002706 }
2707
2708 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2709}
2710
Douglas Gregor319ac892009-04-23 22:29:11 +00002711void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002712 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002713 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2714 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2715}
2716
Anders Carlssone8c49532007-10-29 06:33:42 +00002717// This returns true if a type has been typedefed to BOOL:
2718// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002719static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002720 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002721 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2722 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002723
2724 return false;
2725}
2726
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002727/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002728/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002729int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002730 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002731
2732 // Make all integer and enum types at least as large as an int
2733 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002734 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002735 // Treat arrays as pointers, since that's how they're passed in.
2736 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002737 sz = getTypeSize(VoidPtrTy);
2738 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002739}
2740
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002741/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002742/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002743void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002744 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002745 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002746 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002747 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002748 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002749 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002750 // Compute size of all parameters.
2751 // Start with computing size of a pointer in number of bytes.
2752 // FIXME: There might(should) be a better way of doing this computation!
2753 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002754 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002755 // The first two arguments (self and _cmd) are pointers; account for
2756 // their size.
2757 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002758 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2759 E = Decl->param_end(); PI != E; ++PI) {
2760 QualType PType = (*PI)->getType();
2761 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002762 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002763 ParmOffset += sz;
2764 }
2765 S += llvm::utostr(ParmOffset);
2766 S += "@0:";
2767 S += llvm::utostr(PtrSize);
2768
2769 // Argument types.
2770 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002771 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2772 E = Decl->param_end(); PI != E; ++PI) {
2773 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002774 QualType PType = PVDecl->getOriginalType();
2775 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002776 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2777 // Use array's original type only if it has known number of
2778 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002779 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002780 PType = PVDecl->getType();
2781 } else if (PType->isFunctionType())
2782 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002783 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002784 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002785 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002786 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002787 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002788 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002789 }
2790}
2791
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002792/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002793/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002794/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2795/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002796/// Property attributes are stored as a comma-delimited C string. The simple
2797/// attributes readonly and bycopy are encoded as single characters. The
2798/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2799/// encoded as single characters, followed by an identifier. Property types
2800/// are also encoded as a parametrized attribute. The characters used to encode
2801/// these attributes are defined by the following enumeration:
2802/// @code
2803/// enum PropertyAttributes {
2804/// kPropertyReadOnly = 'R', // property is read-only.
2805/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2806/// kPropertyByref = '&', // property is a reference to the value last assigned
2807/// kPropertyDynamic = 'D', // property is dynamic
2808/// kPropertyGetter = 'G', // followed by getter selector name
2809/// kPropertySetter = 'S', // followed by setter selector name
2810/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2811/// kPropertyType = 't' // followed by old-style type encoding.
2812/// kPropertyWeak = 'W' // 'weak' property
2813/// kPropertyStrong = 'P' // property GC'able
2814/// kPropertyNonAtomic = 'N' // property non-atomic
2815/// };
2816/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002817void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2818 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002819 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002820 // Collect information from the property implementation decl(s).
2821 bool Dynamic = false;
2822 ObjCPropertyImplDecl *SynthesizePID = 0;
2823
2824 // FIXME: Duplicated code due to poor abstraction.
2825 if (Container) {
2826 if (const ObjCCategoryImplDecl *CID =
2827 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2828 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002829 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002830 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002831 ObjCPropertyImplDecl *PID = *i;
2832 if (PID->getPropertyDecl() == PD) {
2833 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2834 Dynamic = true;
2835 } else {
2836 SynthesizePID = PID;
2837 }
2838 }
2839 }
2840 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002841 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002842 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002843 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002844 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002845 ObjCPropertyImplDecl *PID = *i;
2846 if (PID->getPropertyDecl() == PD) {
2847 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2848 Dynamic = true;
2849 } else {
2850 SynthesizePID = PID;
2851 }
2852 }
2853 }
2854 }
2855 }
2856
2857 // FIXME: This is not very efficient.
2858 S = "T";
2859
2860 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002861 // GCC has some special rules regarding encoding of properties which
2862 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002863 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002864 true /* outermost type */,
2865 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002866
2867 if (PD->isReadOnly()) {
2868 S += ",R";
2869 } else {
2870 switch (PD->getSetterKind()) {
2871 case ObjCPropertyDecl::Assign: break;
2872 case ObjCPropertyDecl::Copy: S += ",C"; break;
2873 case ObjCPropertyDecl::Retain: S += ",&"; break;
2874 }
2875 }
2876
2877 // It really isn't clear at all what this means, since properties
2878 // are "dynamic by default".
2879 if (Dynamic)
2880 S += ",D";
2881
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002882 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2883 S += ",N";
2884
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002885 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2886 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002887 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002888 }
2889
2890 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2891 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002892 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002893 }
2894
2895 if (SynthesizePID) {
2896 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2897 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002898 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002899 }
2900
2901 // FIXME: OBJCGC: weak & strong
2902}
2903
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002904/// getLegacyIntegralTypeEncoding -
2905/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002906/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002907/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2908///
2909void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00002910 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002911 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002912 if (BT->getKind() == BuiltinType::ULong &&
2913 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002914 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002915 else
2916 if (BT->getKind() == BuiltinType::Long &&
2917 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002918 PointeeTy = IntTy;
2919 }
2920 }
2921}
2922
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002923void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002924 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002925 // We follow the behavior of gcc, expanding structures which are
2926 // directly pointed to, and expanding embedded structures. Note that
2927 // these rules are sufficient to prevent recursive encoding of the
2928 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002929 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2930 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002931}
2932
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002933static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002934 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002935 const Expr *E = FD->getBitWidth();
2936 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2937 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002938 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002939 S += 'b';
2940 S += llvm::utostr(N);
2941}
2942
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002943void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2944 bool ExpandPointedToStructures,
2945 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002946 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002947 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002948 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002949 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002950 if (FD && FD->isBitField())
2951 return EncodeBitField(this, S, FD);
2952 char encoding;
2953 switch (BT->getKind()) {
2954 default: assert(0 && "Unhandled builtin type kind");
2955 case BuiltinType::Void: encoding = 'v'; break;
2956 case BuiltinType::Bool: encoding = 'B'; break;
2957 case BuiltinType::Char_U:
2958 case BuiltinType::UChar: encoding = 'C'; break;
2959 case BuiltinType::UShort: encoding = 'S'; break;
2960 case BuiltinType::UInt: encoding = 'I'; break;
2961 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002962 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002963 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002964 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002965 case BuiltinType::UInt128: encoding = 'T'; break;
2966 case BuiltinType::ULongLong: encoding = 'Q'; break;
2967 case BuiltinType::Char_S:
2968 case BuiltinType::SChar: encoding = 'c'; break;
2969 case BuiltinType::Short: encoding = 's'; break;
2970 case BuiltinType::Int: encoding = 'i'; break;
2971 case BuiltinType::Long:
2972 encoding =
2973 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2974 break;
2975 case BuiltinType::LongLong: encoding = 'q'; break;
2976 case BuiltinType::Int128: encoding = 't'; break;
2977 case BuiltinType::Float: encoding = 'f'; break;
2978 case BuiltinType::Double: encoding = 'd'; break;
2979 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002980 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002981
2982 S += encoding;
2983 return;
2984 }
2985
2986 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002987 S += 'j';
2988 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2989 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002990 return;
2991 }
2992
Ted Kremenek6217b802009-07-29 21:53:49 +00002993 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002994 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002995 bool isReadOnly = false;
2996 // For historical/compatibility reasons, the read-only qualifier of the
2997 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2998 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2999 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003000 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003001 if (OutermostType && T.isConstQualified()) {
3002 isReadOnly = true;
3003 S += 'r';
3004 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003005 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003006 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003007 while (P->getAs<PointerType>())
3008 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003009 if (P.isConstQualified()) {
3010 isReadOnly = true;
3011 S += 'r';
3012 }
3013 }
3014 if (isReadOnly) {
3015 // Another legacy compatibility encoding. Some ObjC qualifier and type
3016 // combinations need to be rearranged.
3017 // Rewrite "in const" from "nr" to "rn"
3018 const char * s = S.c_str();
3019 int len = S.length();
3020 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3021 std::string replace = "rn";
3022 S.replace(S.end()-2, S.end(), replace);
3023 }
3024 }
Steve Naroff14108da2009-07-10 23:34:53 +00003025 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003026 S += ':';
3027 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003028 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003029
3030 if (PointeeTy->isCharType()) {
3031 // char pointer types should be encoded as '*' unless it is a
3032 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003033 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003034 S += '*';
3035 return;
3036 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003037 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003038 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3039 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3040 S += '#';
3041 return;
3042 }
3043 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3044 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3045 S += '@';
3046 return;
3047 }
3048 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003049 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003050 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003051 getLegacyIntegralTypeEncoding(PointeeTy);
3052
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003053 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003054 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003055 return;
3056 }
3057
3058 if (const ArrayType *AT =
3059 // Ignore type qualifiers etc.
3060 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003061 if (isa<IncompleteArrayType>(AT)) {
3062 // Incomplete arrays are encoded as a pointer to the array element.
3063 S += '^';
3064
3065 getObjCEncodingForTypeImpl(AT->getElementType(), S,
3066 false, ExpandStructures, FD);
3067 } else {
3068 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003069
Anders Carlsson559a8332009-02-22 01:38:57 +00003070 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3071 S += llvm::utostr(CAT->getSize().getZExtValue());
3072 else {
3073 //Variable length arrays are encoded as a regular array with 0 elements.
3074 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3075 S += '0';
3076 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003077
Anders Carlsson559a8332009-02-22 01:38:57 +00003078 getObjCEncodingForTypeImpl(AT->getElementType(), S,
3079 false, ExpandStructures, FD);
3080 S += ']';
3081 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003082 return;
3083 }
3084
3085 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003086 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003087 return;
3088 }
3089
Ted Kremenek6217b802009-07-29 21:53:49 +00003090 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003091 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003092 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003093 // Anonymous structures print as '?'
3094 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3095 S += II->getName();
3096 } else {
3097 S += '?';
3098 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003099 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003100 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003101 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3102 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003103 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003104 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003105 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003106 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003107 S += '"';
3108 }
3109
3110 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003111 if (Field->isBitField()) {
3112 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3113 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003114 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003115 QualType qt = Field->getType();
3116 getLegacyIntegralTypeEncoding(qt);
3117 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003118 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003119 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003120 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003121 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003122 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003123 return;
3124 }
3125
3126 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003127 if (FD && FD->isBitField())
3128 EncodeBitField(this, S, FD);
3129 else
3130 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003131 return;
3132 }
3133
3134 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003135 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003136 return;
3137 }
3138
3139 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003140 // @encode(class_name)
3141 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
3142 S += '{';
3143 const IdentifierInfo *II = OI->getIdentifier();
3144 S += II->getName();
3145 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003146 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003147 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003148 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003149 if (RecFields[i]->isBitField())
3150 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3151 RecFields[i]);
3152 else
3153 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3154 FD);
3155 }
3156 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003157 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003158 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003159
3160 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003161 if (OPT->isObjCIdType()) {
3162 S += '@';
3163 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003164 }
3165
3166 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003167 S += '#';
3168 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003169 }
3170
3171 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003172 getObjCEncodingForTypeImpl(getObjCIdType(), S,
3173 ExpandPointedToStructures,
3174 ExpandStructures, FD);
3175 if (FD || EncodingProperty) {
3176 // Note that we do extended encoding of protocol qualifer list
3177 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003178 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003179 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3180 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003181 S += '<';
3182 S += (*I)->getNameAsString();
3183 S += '>';
3184 }
3185 S += '"';
3186 }
3187 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003188 }
3189
3190 QualType PointeeTy = OPT->getPointeeType();
3191 if (!EncodingProperty &&
3192 isa<TypedefType>(PointeeTy.getTypePtr())) {
3193 // Another historical/compatibility reason.
3194 // We encode the underlying type which comes out as
3195 // {...};
3196 S += '^';
3197 getObjCEncodingForTypeImpl(PointeeTy, S,
3198 false, ExpandPointedToStructures,
3199 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003200 return;
3201 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003202
3203 S += '@';
3204 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003205 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003206 S += OPT->getInterfaceDecl()->getNameAsCString();
3207 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3208 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003209 S += '<';
3210 S += (*I)->getNameAsString();
3211 S += '>';
3212 }
3213 S += '"';
3214 }
3215 return;
3216 }
3217
3218 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003219}
3220
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003221void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003222 std::string& S) const {
3223 if (QT & Decl::OBJC_TQ_In)
3224 S += 'n';
3225 if (QT & Decl::OBJC_TQ_Inout)
3226 S += 'N';
3227 if (QT & Decl::OBJC_TQ_Out)
3228 S += 'o';
3229 if (QT & Decl::OBJC_TQ_Bycopy)
3230 S += 'O';
3231 if (QT & Decl::OBJC_TQ_Byref)
3232 S += 'R';
3233 if (QT & Decl::OBJC_TQ_Oneway)
3234 S += 'V';
3235}
3236
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003237void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003238 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3239
3240 BuiltinVaListType = T;
3241}
3242
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003243void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003244 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003245}
3246
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003247void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003248 ObjCSelType = T;
3249
3250 const TypedefType *TT = T->getAsTypedefType();
3251 if (!TT)
3252 return;
3253 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003254
3255 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003256 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003257 if (!ptr)
3258 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003259 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003260 if (!rec)
3261 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003262 SelStructType = rec;
3263}
3264
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003265void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003266 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003267}
3268
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003269void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003270 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003271}
3272
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003273void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3274 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003275 "'NSConstantString' type already set!");
3276
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003277 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003278}
3279
Douglas Gregor7532dc62009-03-30 22:58:21 +00003280/// \brief Retrieve the template name that represents a qualified
3281/// template name such as \c std::vector.
3282TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3283 bool TemplateKeyword,
3284 TemplateDecl *Template) {
3285 llvm::FoldingSetNodeID ID;
3286 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3287
3288 void *InsertPos = 0;
3289 QualifiedTemplateName *QTN =
3290 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3291 if (!QTN) {
3292 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3293 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3294 }
3295
3296 return TemplateName(QTN);
3297}
3298
Douglas Gregord99cbe62009-07-29 18:26:50 +00003299/// \brief Retrieve the template name that represents a qualified
3300/// template name such as \c std::vector.
3301TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3302 bool TemplateKeyword,
3303 OverloadedFunctionDecl *Template) {
3304 llvm::FoldingSetNodeID ID;
3305 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3306
3307 void *InsertPos = 0;
3308 QualifiedTemplateName *QTN =
3309 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3310 if (!QTN) {
3311 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3312 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3313 }
3314
3315 return TemplateName(QTN);
3316}
3317
Douglas Gregor7532dc62009-03-30 22:58:21 +00003318/// \brief Retrieve the template name that represents a dependent
3319/// template name such as \c MetaFun::template apply.
3320TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3321 const IdentifierInfo *Name) {
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003322 assert((!NNS || NNS->isDependent()) &&
3323 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003324
3325 llvm::FoldingSetNodeID ID;
3326 DependentTemplateName::Profile(ID, NNS, Name);
3327
3328 void *InsertPos = 0;
3329 DependentTemplateName *QTN =
3330 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3331
3332 if (QTN)
3333 return TemplateName(QTN);
3334
3335 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3336 if (CanonNNS == NNS) {
3337 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3338 } else {
3339 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3340 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3341 }
3342
3343 DependentTemplateNames.InsertNode(QTN, InsertPos);
3344 return TemplateName(QTN);
3345}
3346
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003347/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003348/// TargetInfo, produce the corresponding type. The unsigned @p Type
3349/// is actually a value of type @c TargetInfo::IntType.
3350QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003351 switch (Type) {
3352 case TargetInfo::NoInt: return QualType();
3353 case TargetInfo::SignedShort: return ShortTy;
3354 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3355 case TargetInfo::SignedInt: return IntTy;
3356 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3357 case TargetInfo::SignedLong: return LongTy;
3358 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3359 case TargetInfo::SignedLongLong: return LongLongTy;
3360 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3361 }
3362
3363 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003364 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003365}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003366
3367//===----------------------------------------------------------------------===//
3368// Type Predicates.
3369//===----------------------------------------------------------------------===//
3370
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003371/// isObjCNSObjectType - Return true if this is an NSObject object using
3372/// NSObject attribute on a c-style pointer type.
3373/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003374/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003375///
3376bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3377 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3378 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003379 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003380 return true;
3381 }
3382 return false;
3383}
3384
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003385/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3386/// garbage collection attribute.
3387///
3388QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003389 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003390 if (getLangOptions().ObjC1 &&
3391 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003392 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003393 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003394 // (or pointers to them) be treated as though they were declared
3395 // as __strong.
3396 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003397 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003398 GCAttrs = QualType::Strong;
3399 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003400 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003401 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003402 // Non-pointers have none gc'able attribute regardless of the attribute
3403 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003404 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003405 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003406 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003407 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003408}
3409
Chris Lattner6ac46a42008-04-07 06:51:04 +00003410//===----------------------------------------------------------------------===//
3411// Type Compatibility Testing
3412//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003413
Chris Lattner6ac46a42008-04-07 06:51:04 +00003414/// areCompatVectorTypes - Return true if the two specified vector types are
3415/// compatible.
3416static bool areCompatVectorTypes(const VectorType *LHS,
3417 const VectorType *RHS) {
3418 assert(LHS->isCanonical() && RHS->isCanonical());
3419 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003420 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003421}
3422
Steve Naroff4084c302009-07-23 01:01:38 +00003423//===----------------------------------------------------------------------===//
3424// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3425//===----------------------------------------------------------------------===//
3426
3427/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3428/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003429bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3430 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003431 if (lProto == rProto)
3432 return true;
3433 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3434 E = rProto->protocol_end(); PI != E; ++PI)
3435 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3436 return true;
3437 return false;
3438}
3439
Steve Naroff4084c302009-07-23 01:01:38 +00003440/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3441/// return true if lhs's protocols conform to rhs's protocol; false
3442/// otherwise.
3443bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3444 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3445 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3446 return false;
3447}
3448
3449/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3450/// ObjCQualifiedIDType.
3451bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3452 bool compare) {
3453 // Allow id<P..> and an 'id' or void* type in all cases.
3454 if (lhs->isVoidPointerType() ||
3455 lhs->isObjCIdType() || lhs->isObjCClassType())
3456 return true;
3457 else if (rhs->isVoidPointerType() ||
3458 rhs->isObjCIdType() || rhs->isObjCClassType())
3459 return true;
3460
3461 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3462 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3463
3464 if (!rhsOPT) return false;
3465
3466 if (rhsOPT->qual_empty()) {
3467 // If the RHS is a unqualified interface pointer "NSString*",
3468 // make sure we check the class hierarchy.
3469 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3470 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3471 E = lhsQID->qual_end(); I != E; ++I) {
3472 // when comparing an id<P> on lhs with a static type on rhs,
3473 // see if static class implements all of id's protocols, directly or
3474 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003475 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003476 return false;
3477 }
3478 }
3479 // If there are no qualifiers and no interface, we have an 'id'.
3480 return true;
3481 }
3482 // Both the right and left sides have qualifiers.
3483 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3484 E = lhsQID->qual_end(); I != E; ++I) {
3485 ObjCProtocolDecl *lhsProto = *I;
3486 bool match = false;
3487
3488 // when comparing an id<P> on lhs with a static type on rhs,
3489 // see if static class implements all of id's protocols, directly or
3490 // through its super class and categories.
3491 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3492 E = rhsOPT->qual_end(); J != E; ++J) {
3493 ObjCProtocolDecl *rhsProto = *J;
3494 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3495 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3496 match = true;
3497 break;
3498 }
3499 }
3500 // If the RHS is a qualified interface pointer "NSString<P>*",
3501 // make sure we check the class hierarchy.
3502 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3503 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3504 E = lhsQID->qual_end(); I != E; ++I) {
3505 // when comparing an id<P> on lhs with a static type on rhs,
3506 // see if static class implements all of id's protocols, directly or
3507 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003508 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003509 match = true;
3510 break;
3511 }
3512 }
3513 }
3514 if (!match)
3515 return false;
3516 }
3517
3518 return true;
3519 }
3520
3521 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3522 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3523
3524 if (const ObjCObjectPointerType *lhsOPT =
3525 lhs->getAsObjCInterfacePointerType()) {
3526 if (lhsOPT->qual_empty()) {
3527 bool match = false;
3528 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3529 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3530 E = rhsQID->qual_end(); I != E; ++I) {
3531 // when comparing an id<P> on lhs with a static type on rhs,
3532 // see if static class implements all of id's protocols, directly or
3533 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003534 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003535 match = true;
3536 break;
3537 }
3538 }
3539 if (!match)
3540 return false;
3541 }
3542 return true;
3543 }
3544 // Both the right and left sides have qualifiers.
3545 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3546 E = lhsOPT->qual_end(); I != E; ++I) {
3547 ObjCProtocolDecl *lhsProto = *I;
3548 bool match = false;
3549
3550 // when comparing an id<P> on lhs with a static type on rhs,
3551 // see if static class implements all of id's protocols, directly or
3552 // through its super class and categories.
3553 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3554 E = rhsQID->qual_end(); J != E; ++J) {
3555 ObjCProtocolDecl *rhsProto = *J;
3556 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3557 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3558 match = true;
3559 break;
3560 }
3561 }
3562 if (!match)
3563 return false;
3564 }
3565 return true;
3566 }
3567 return false;
3568}
3569
Eli Friedman3d815e72008-08-22 00:56:42 +00003570/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003571/// compatible for assignment from RHS to LHS. This handles validation of any
3572/// protocol qualifiers on the LHS or RHS.
3573///
Steve Naroff14108da2009-07-10 23:34:53 +00003574bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3575 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003576 // If either type represents the built-in 'id' or 'Class' types, return true.
3577 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003578 return true;
3579
Steve Naroff4084c302009-07-23 01:01:38 +00003580 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3581 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3582 QualType(RHSOPT,0),
3583 false);
3584
Steve Naroff14108da2009-07-10 23:34:53 +00003585 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3586 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003587 if (LHS && RHS) // We have 2 user-defined types.
3588 return canAssignObjCInterfaces(LHS, RHS);
3589
3590 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003591}
3592
Eli Friedman3d815e72008-08-22 00:56:42 +00003593bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3594 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003595 // Verify that the base decls are compatible: the RHS must be a subclass of
3596 // the LHS.
3597 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3598 return false;
3599
3600 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3601 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003602 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003603 return true;
3604
3605 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3606 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003607 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003608 return true; // FIXME: should return false!
3609
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003610 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3611 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003612 LHSPI != LHSPE; LHSPI++) {
3613 bool RHSImplementsProtocol = false;
3614
3615 // If the RHS doesn't implement the protocol on the left, the types
3616 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003617 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003618 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003619 RHSPI != RHSPE; RHSPI++) {
3620 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003621 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003622 break;
3623 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003624 }
3625 // FIXME: For better diagnostics, consider passing back the protocol name.
3626 if (!RHSImplementsProtocol)
3627 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003628 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003629 // The RHS implements all protocols listed on the LHS.
3630 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003631}
3632
Steve Naroff389bf462009-02-12 17:52:19 +00003633bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3634 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003635 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3636 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003637
Steve Naroff14108da2009-07-10 23:34:53 +00003638 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003639 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003640
3641 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3642 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003643}
3644
Steve Naroffec0550f2007-10-15 20:41:53 +00003645/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3646/// both shall have the identically qualified version of a compatible type.
3647/// C99 6.2.7p1: Two types have compatible types if their types are the
3648/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003649bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3650 return !mergeTypes(LHS, RHS).isNull();
3651}
3652
3653QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3654 const FunctionType *lbase = lhs->getAsFunctionType();
3655 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003656 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3657 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003658 bool allLTypes = true;
3659 bool allRTypes = true;
3660
3661 // Check return type
3662 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3663 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003664 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3665 allLTypes = false;
3666 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3667 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003668 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003669 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3670 if (NoReturn != lbase->getNoReturnAttr())
3671 allLTypes = false;
3672 if (NoReturn != rbase->getNoReturnAttr())
3673 allRTypes = false;
3674
Eli Friedman3d815e72008-08-22 00:56:42 +00003675 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003676 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3677 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003678 unsigned lproto_nargs = lproto->getNumArgs();
3679 unsigned rproto_nargs = rproto->getNumArgs();
3680
3681 // Compatible functions must have the same number of arguments
3682 if (lproto_nargs != rproto_nargs)
3683 return QualType();
3684
3685 // Variadic and non-variadic functions aren't compatible
3686 if (lproto->isVariadic() != rproto->isVariadic())
3687 return QualType();
3688
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003689 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3690 return QualType();
3691
Eli Friedman3d815e72008-08-22 00:56:42 +00003692 // Check argument compatibility
3693 llvm::SmallVector<QualType, 10> types;
3694 for (unsigned i = 0; i < lproto_nargs; i++) {
3695 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3696 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3697 QualType argtype = mergeTypes(largtype, rargtype);
3698 if (argtype.isNull()) return QualType();
3699 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003700 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3701 allLTypes = false;
3702 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3703 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003704 }
3705 if (allLTypes) return lhs;
3706 if (allRTypes) return rhs;
3707 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003708 lproto->isVariadic(), lproto->getTypeQuals(),
3709 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003710 }
3711
3712 if (lproto) allRTypes = false;
3713 if (rproto) allLTypes = false;
3714
Douglas Gregor72564e72009-02-26 23:50:07 +00003715 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003716 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003717 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003718 if (proto->isVariadic()) return QualType();
3719 // Check that the types are compatible with the types that
3720 // would result from default argument promotions (C99 6.7.5.3p15).
3721 // The only types actually affected are promotable integer
3722 // types and floats, which would be passed as a different
3723 // type depending on whether the prototype is visible.
3724 unsigned proto_nargs = proto->getNumArgs();
3725 for (unsigned i = 0; i < proto_nargs; ++i) {
3726 QualType argTy = proto->getArgType(i);
3727 if (argTy->isPromotableIntegerType() ||
3728 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3729 return QualType();
3730 }
3731
3732 if (allLTypes) return lhs;
3733 if (allRTypes) return rhs;
3734 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003735 proto->getNumArgs(), proto->isVariadic(),
3736 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003737 }
3738
3739 if (allLTypes) return lhs;
3740 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003741 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003742}
3743
3744QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003745 // C++ [expr]: If an expression initially has the type "reference to T", the
3746 // type is adjusted to "T" prior to any further analysis, the expression
3747 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003748 // expression is an lvalue unless the reference is an rvalue reference and
3749 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003750 // FIXME: C++ shouldn't be going through here! The rules are different
3751 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003752 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3753 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003754 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003755 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003756 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003757 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003758
Eli Friedman3d815e72008-08-22 00:56:42 +00003759 QualType LHSCan = getCanonicalType(LHS),
3760 RHSCan = getCanonicalType(RHS);
3761
3762 // If two types are identical, they are compatible.
3763 if (LHSCan == RHSCan)
3764 return LHS;
3765
3766 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003767 // Note that we handle extended qualifiers later, in the
3768 // case for ExtQualType.
3769 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003770 return QualType();
3771
Eli Friedman852d63b2009-06-01 01:22:52 +00003772 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3773 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003774
Chris Lattner1adb8832008-01-14 05:45:46 +00003775 // We want to consider the two function types to be the same for these
3776 // comparisons, just force one to the other.
3777 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3778 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003779
Eli Friedman07d25872009-06-02 05:28:56 +00003780 // Strip off objc_gc attributes off the top level so they can be merged.
3781 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003782 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003783 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3784 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003785 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003786 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003787 // __strong attribue is redundant if other decl is an objective-c
3788 // object pointer (or decorated with __strong attribute); otherwise
3789 // issue error.
3790 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3791 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003792 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003793 return QualType();
3794
Eli Friedman07d25872009-06-02 05:28:56 +00003795 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3796 RHS.getCVRQualifiers());
3797 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003798 if (!Result.isNull()) {
3799 if (Result.getObjCGCAttr() == QualType::GCNone)
3800 Result = getObjCGCQualType(Result, GCAttr);
3801 else if (Result.getObjCGCAttr() != GCAttr)
3802 Result = QualType();
3803 }
Eli Friedman07d25872009-06-02 05:28:56 +00003804 return Result;
3805 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003806 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003807 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003808 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3809 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003810 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3811 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003812 // __strong attribue is redundant if other decl is an objective-c
3813 // object pointer (or decorated with __strong attribute); otherwise
3814 // issue error.
3815 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3816 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003817 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003818 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003819
Eli Friedman07d25872009-06-02 05:28:56 +00003820 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3821 LHS.getCVRQualifiers());
3822 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003823 if (!Result.isNull()) {
3824 if (Result.getObjCGCAttr() == QualType::GCNone)
3825 Result = getObjCGCQualType(Result, GCAttr);
3826 else if (Result.getObjCGCAttr() != GCAttr)
3827 Result = QualType();
3828 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003829 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003830 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003831 }
3832
Eli Friedman4c721d32008-02-12 08:23:06 +00003833 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003834 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3835 LHSClass = Type::ConstantArray;
3836 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3837 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003838
Nate Begeman213541a2008-04-18 23:10:10 +00003839 // Canonicalize ExtVector -> Vector.
3840 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3841 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003842
3843 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003844 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003845 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3846 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003847 if (const EnumType* ETy = LHS->getAsEnumType()) {
3848 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3849 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003850 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003851 if (const EnumType* ETy = RHS->getAsEnumType()) {
3852 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3853 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003854 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003855
Eli Friedman3d815e72008-08-22 00:56:42 +00003856 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003857 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003858
Steve Naroff4a746782008-01-09 22:43:08 +00003859 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003860 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003861#define TYPE(Class, Base)
3862#define ABSTRACT_TYPE(Class, Base)
3863#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3864#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3865#include "clang/AST/TypeNodes.def"
3866 assert(false && "Non-canonical and dependent types shouldn't get here");
3867 return QualType();
3868
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003869 case Type::LValueReference:
3870 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003871 case Type::MemberPointer:
3872 assert(false && "C++ should never be in mergeTypes");
3873 return QualType();
3874
3875 case Type::IncompleteArray:
3876 case Type::VariableArray:
3877 case Type::FunctionProto:
3878 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003879 assert(false && "Types are eliminated above");
3880 return QualType();
3881
Chris Lattner1adb8832008-01-14 05:45:46 +00003882 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003883 {
3884 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003885 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
3886 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003887 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3888 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003889 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003890 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003891 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003892 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003893 return getPointerType(ResultType);
3894 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003895 case Type::BlockPointer:
3896 {
3897 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003898 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
3899 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003900 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3901 if (ResultType.isNull()) return QualType();
3902 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3903 return LHS;
3904 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3905 return RHS;
3906 return getBlockPointerType(ResultType);
3907 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003908 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003909 {
3910 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3911 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3912 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3913 return QualType();
3914
3915 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3916 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3917 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3918 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003919 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3920 return LHS;
3921 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3922 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003923 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3924 ArrayType::ArraySizeModifier(), 0);
3925 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3926 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003927 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3928 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003929 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3930 return LHS;
3931 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3932 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003933 if (LVAT) {
3934 // FIXME: This isn't correct! But tricky to implement because
3935 // the array's size has to be the size of LHS, but the type
3936 // has to be different.
3937 return LHS;
3938 }
3939 if (RVAT) {
3940 // FIXME: This isn't correct! But tricky to implement because
3941 // the array's size has to be the size of RHS, but the type
3942 // has to be different.
3943 return RHS;
3944 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003945 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3946 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003947 return getIncompleteArrayType(ResultType,
3948 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003949 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003950 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003951 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003952 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003953 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003954 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003955 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003956 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003957 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003958 case Type::Complex:
3959 // Distinct complex types are incompatible.
3960 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003961 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003962 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003963 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3964 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003965 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003966 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003967 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003968 // FIXME: This should be type compatibility, e.g. whether
3969 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003970 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3971 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3972 if (LHSIface && RHSIface &&
3973 canAssignObjCInterfaces(LHSIface, RHSIface))
3974 return LHS;
3975
Eli Friedman3d815e72008-08-22 00:56:42 +00003976 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003977 }
Steve Naroff14108da2009-07-10 23:34:53 +00003978 case Type::ObjCObjectPointer: {
Steve Naroff14108da2009-07-10 23:34:53 +00003979 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3980 RHS->getAsObjCObjectPointerType()))
3981 return LHS;
3982
Steve Naroffbc76dd02008-12-10 22:14:21 +00003983 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003984 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003985 case Type::FixedWidthInt:
3986 // Distinct fixed-width integers are not compatible.
3987 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003988 case Type::ExtQual:
3989 // FIXME: ExtQual types can be compatible even if they're not
3990 // identical!
3991 return QualType();
3992 // First attempt at an implementation, but I'm not really sure it's
3993 // right...
3994#if 0
3995 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3996 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3997 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3998 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3999 return QualType();
4000 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
4001 LHSBase = QualType(LQual->getBaseType(), 0);
4002 RHSBase = QualType(RQual->getBaseType(), 0);
4003 ResultType = mergeTypes(LHSBase, RHSBase);
4004 if (ResultType.isNull()) return QualType();
4005 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
4006 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
4007 return LHS;
4008 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
4009 return RHS;
4010 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
4011 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
4012 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
4013 return ResultType;
4014#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00004015
4016 case Type::TemplateSpecialization:
4017 assert(false && "Dependent types have no size");
4018 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004019 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004020
4021 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004022}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004023
Chris Lattner5426bf62008-04-07 07:01:58 +00004024//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004025// Integer Predicates
4026//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004027
Eli Friedmanad74a752008-06-28 06:23:08 +00004028unsigned ASTContext::getIntWidth(QualType T) {
4029 if (T == BoolTy)
4030 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00004031 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
4032 return FWIT->getWidth();
4033 }
4034 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004035 return (unsigned)getTypeSize(T);
4036}
4037
4038QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4039 assert(T->isSignedIntegerType() && "Unexpected type");
4040 if (const EnumType* ETy = T->getAsEnumType())
4041 T = ETy->getDecl()->getIntegerType();
4042 const BuiltinType* BTy = T->getAsBuiltinType();
4043 assert (BTy && "Unexpected signed integer type");
4044 switch (BTy->getKind()) {
4045 case BuiltinType::Char_S:
4046 case BuiltinType::SChar:
4047 return UnsignedCharTy;
4048 case BuiltinType::Short:
4049 return UnsignedShortTy;
4050 case BuiltinType::Int:
4051 return UnsignedIntTy;
4052 case BuiltinType::Long:
4053 return UnsignedLongTy;
4054 case BuiltinType::LongLong:
4055 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004056 case BuiltinType::Int128:
4057 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004058 default:
4059 assert(0 && "Unexpected signed integer type");
4060 return QualType();
4061 }
4062}
4063
Douglas Gregor2cf26342009-04-09 22:27:44 +00004064ExternalASTSource::~ExternalASTSource() { }
4065
4066void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004067
4068
4069//===----------------------------------------------------------------------===//
4070// Builtin Type Computation
4071//===----------------------------------------------------------------------===//
4072
4073/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4074/// pointer over the consumed characters. This returns the resultant type.
4075static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4076 ASTContext::GetBuiltinTypeError &Error,
4077 bool AllowTypeModifiers = true) {
4078 // Modifiers.
4079 int HowLong = 0;
4080 bool Signed = false, Unsigned = false;
4081
4082 // Read the modifiers first.
4083 bool Done = false;
4084 while (!Done) {
4085 switch (*Str++) {
4086 default: Done = true; --Str; break;
4087 case 'S':
4088 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4089 assert(!Signed && "Can't use 'S' modifier multiple times!");
4090 Signed = true;
4091 break;
4092 case 'U':
4093 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4094 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4095 Unsigned = true;
4096 break;
4097 case 'L':
4098 assert(HowLong <= 2 && "Can't have LLLL modifier");
4099 ++HowLong;
4100 break;
4101 }
4102 }
4103
4104 QualType Type;
4105
4106 // Read the base type.
4107 switch (*Str++) {
4108 default: assert(0 && "Unknown builtin type letter!");
4109 case 'v':
4110 assert(HowLong == 0 && !Signed && !Unsigned &&
4111 "Bad modifiers used with 'v'!");
4112 Type = Context.VoidTy;
4113 break;
4114 case 'f':
4115 assert(HowLong == 0 && !Signed && !Unsigned &&
4116 "Bad modifiers used with 'f'!");
4117 Type = Context.FloatTy;
4118 break;
4119 case 'd':
4120 assert(HowLong < 2 && !Signed && !Unsigned &&
4121 "Bad modifiers used with 'd'!");
4122 if (HowLong)
4123 Type = Context.LongDoubleTy;
4124 else
4125 Type = Context.DoubleTy;
4126 break;
4127 case 's':
4128 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4129 if (Unsigned)
4130 Type = Context.UnsignedShortTy;
4131 else
4132 Type = Context.ShortTy;
4133 break;
4134 case 'i':
4135 if (HowLong == 3)
4136 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4137 else if (HowLong == 2)
4138 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4139 else if (HowLong == 1)
4140 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4141 else
4142 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4143 break;
4144 case 'c':
4145 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4146 if (Signed)
4147 Type = Context.SignedCharTy;
4148 else if (Unsigned)
4149 Type = Context.UnsignedCharTy;
4150 else
4151 Type = Context.CharTy;
4152 break;
4153 case 'b': // boolean
4154 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4155 Type = Context.BoolTy;
4156 break;
4157 case 'z': // size_t.
4158 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4159 Type = Context.getSizeType();
4160 break;
4161 case 'F':
4162 Type = Context.getCFConstantStringType();
4163 break;
4164 case 'a':
4165 Type = Context.getBuiltinVaListType();
4166 assert(!Type.isNull() && "builtin va list type not initialized!");
4167 break;
4168 case 'A':
4169 // This is a "reference" to a va_list; however, what exactly
4170 // this means depends on how va_list is defined. There are two
4171 // different kinds of va_list: ones passed by value, and ones
4172 // passed by reference. An example of a by-value va_list is
4173 // x86, where va_list is a char*. An example of by-ref va_list
4174 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4175 // we want this argument to be a char*&; for x86-64, we want
4176 // it to be a __va_list_tag*.
4177 Type = Context.getBuiltinVaListType();
4178 assert(!Type.isNull() && "builtin va list type not initialized!");
4179 if (Type->isArrayType()) {
4180 Type = Context.getArrayDecayedType(Type);
4181 } else {
4182 Type = Context.getLValueReferenceType(Type);
4183 }
4184 break;
4185 case 'V': {
4186 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004187 unsigned NumElements = strtoul(Str, &End, 10);
4188 assert(End != Str && "Missing vector size");
4189
4190 Str = End;
4191
4192 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4193 Type = Context.getVectorType(ElementType, NumElements);
4194 break;
4195 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004196 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004197 Type = Context.getFILEType();
4198 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004199 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004200 return QualType();
4201 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004202 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004203 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004204 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004205 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004206 else
4207 Type = Context.getjmp_bufType();
4208
Mike Stumpfd612db2009-07-28 23:47:15 +00004209 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004210 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004211 return QualType();
4212 }
4213 break;
Mike Stump782fa302009-07-28 02:25:19 +00004214 }
Chris Lattner86df27b2009-06-14 00:45:47 +00004215
4216 if (!AllowTypeModifiers)
4217 return Type;
4218
4219 Done = false;
4220 while (!Done) {
4221 switch (*Str++) {
4222 default: Done = true; --Str; break;
4223 case '*':
4224 Type = Context.getPointerType(Type);
4225 break;
4226 case '&':
4227 Type = Context.getLValueReferenceType(Type);
4228 break;
4229 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4230 case 'C':
4231 Type = Type.getQualifiedType(QualType::Const);
4232 break;
4233 }
4234 }
4235
4236 return Type;
4237}
4238
4239/// GetBuiltinType - Return the type for the specified builtin.
4240QualType ASTContext::GetBuiltinType(unsigned id,
4241 GetBuiltinTypeError &Error) {
4242 const char *TypeStr = BuiltinInfo.GetTypeString(id);
4243
4244 llvm::SmallVector<QualType, 8> ArgTypes;
4245
4246 Error = GE_None;
4247 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4248 if (Error != GE_None)
4249 return QualType();
4250 while (TypeStr[0] && TypeStr[0] != '.') {
4251 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4252 if (Error != GE_None)
4253 return QualType();
4254
4255 // Do array -> pointer decay. The builtin should use the decayed type.
4256 if (Ty->isArrayType())
4257 Ty = getArrayDecayedType(Ty);
4258
4259 ArgTypes.push_back(Ty);
4260 }
4261
4262 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4263 "'.' should only occur at end of builtin type list!");
4264
4265 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4266 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4267 return getFunctionNoProtoType(ResType);
4268 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4269 TypeStr[0] == '.', 0);
4270}
Eli Friedmana95d7572009-08-19 07:44:53 +00004271
4272QualType
4273ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4274 // Perform the usual unary conversions. We do this early so that
4275 // integral promotions to "int" can allow us to exit early, in the
4276 // lhs == rhs check. Also, for conversion purposes, we ignore any
4277 // qualifiers. For example, "const float" and "float" are
4278 // equivalent.
4279 if (lhs->isPromotableIntegerType())
4280 lhs = getPromotedIntegerType(lhs);
4281 else
4282 lhs = lhs.getUnqualifiedType();
4283 if (rhs->isPromotableIntegerType())
4284 rhs = getPromotedIntegerType(rhs);
4285 else
4286 rhs = rhs.getUnqualifiedType();
4287
4288 // If both types are identical, no conversion is needed.
4289 if (lhs == rhs)
4290 return lhs;
4291
4292 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4293 // The caller can deal with this (e.g. pointer + int).
4294 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4295 return lhs;
4296
4297 // At this point, we have two different arithmetic types.
4298
4299 // Handle complex types first (C99 6.3.1.8p1).
4300 if (lhs->isComplexType() || rhs->isComplexType()) {
4301 // if we have an integer operand, the result is the complex type.
4302 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4303 // convert the rhs to the lhs complex type.
4304 return lhs;
4305 }
4306 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4307 // convert the lhs to the rhs complex type.
4308 return rhs;
4309 }
4310 // This handles complex/complex, complex/float, or float/complex.
4311 // When both operands are complex, the shorter operand is converted to the
4312 // type of the longer, and that is the type of the result. This corresponds
4313 // to what is done when combining two real floating-point operands.
4314 // The fun begins when size promotion occur across type domains.
4315 // From H&S 6.3.4: When one operand is complex and the other is a real
4316 // floating-point type, the less precise type is converted, within it's
4317 // real or complex domain, to the precision of the other type. For example,
4318 // when combining a "long double" with a "double _Complex", the
4319 // "double _Complex" is promoted to "long double _Complex".
4320 int result = getFloatingTypeOrder(lhs, rhs);
4321
4322 if (result > 0) { // The left side is bigger, convert rhs.
4323 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4324 } else if (result < 0) { // The right side is bigger, convert lhs.
4325 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4326 }
4327 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4328 // domains match. This is a requirement for our implementation, C99
4329 // does not require this promotion.
4330 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4331 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4332 return rhs;
4333 } else { // handle "_Complex double, double".
4334 return lhs;
4335 }
4336 }
4337 return lhs; // The domain/size match exactly.
4338 }
4339 // Now handle "real" floating types (i.e. float, double, long double).
4340 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4341 // if we have an integer operand, the result is the real floating type.
4342 if (rhs->isIntegerType()) {
4343 // convert rhs to the lhs floating point type.
4344 return lhs;
4345 }
4346 if (rhs->isComplexIntegerType()) {
4347 // convert rhs to the complex floating point type.
4348 return getComplexType(lhs);
4349 }
4350 if (lhs->isIntegerType()) {
4351 // convert lhs to the rhs floating point type.
4352 return rhs;
4353 }
4354 if (lhs->isComplexIntegerType()) {
4355 // convert lhs to the complex floating point type.
4356 return getComplexType(rhs);
4357 }
4358 // We have two real floating types, float/complex combos were handled above.
4359 // Convert the smaller operand to the bigger result.
4360 int result = getFloatingTypeOrder(lhs, rhs);
4361 if (result > 0) // convert the rhs
4362 return lhs;
4363 assert(result < 0 && "illegal float comparison");
4364 return rhs; // convert the lhs
4365 }
4366 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4367 // Handle GCC complex int extension.
4368 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4369 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4370
4371 if (lhsComplexInt && rhsComplexInt) {
4372 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4373 rhsComplexInt->getElementType()) >= 0)
4374 return lhs; // convert the rhs
4375 return rhs;
4376 } else if (lhsComplexInt && rhs->isIntegerType()) {
4377 // convert the rhs to the lhs complex type.
4378 return lhs;
4379 } else if (rhsComplexInt && lhs->isIntegerType()) {
4380 // convert the lhs to the rhs complex type.
4381 return rhs;
4382 }
4383 }
4384 // Finally, we have two differing integer types.
4385 // The rules for this case are in C99 6.3.1.8
4386 int compare = getIntegerTypeOrder(lhs, rhs);
4387 bool lhsSigned = lhs->isSignedIntegerType(),
4388 rhsSigned = rhs->isSignedIntegerType();
4389 QualType destType;
4390 if (lhsSigned == rhsSigned) {
4391 // Same signedness; use the higher-ranked type
4392 destType = compare >= 0 ? lhs : rhs;
4393 } else if (compare != (lhsSigned ? 1 : -1)) {
4394 // The unsigned type has greater than or equal rank to the
4395 // signed type, so use the unsigned type
4396 destType = lhsSigned ? rhs : lhs;
4397 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4398 // The two types are different widths; if we are here, that
4399 // means the signed type is larger than the unsigned type, so
4400 // use the signed type.
4401 destType = lhsSigned ? lhs : rhs;
4402 } else {
4403 // The signed type is higher-ranked than the unsigned type,
4404 // but isn't actually any bigger (like unsigned int and long
4405 // on most 32-bit systems). Use the unsigned type corresponding
4406 // to the signed type.
4407 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4408 }
4409 return destType;
4410}