blob: 1143b305add0e539bf5f3cecff72f2881450aad3 [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
Douglas Gregor18857642009-04-30 17:32:17 +0000736 case Type::Typedef: {
737 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000738 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000739 Align = Aligned->getAlignment();
740 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
741 } else
742 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000743 break;
Chris Lattner71763312008-04-06 22:05:18 +0000744 }
Douglas Gregor18857642009-04-30 17:32:17 +0000745
746 case Type::TypeOfExpr:
747 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
748 .getTypePtr());
749
750 case Type::TypeOf:
751 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
752
Anders Carlsson395b4752009-06-24 19:06:50 +0000753 case Type::Decltype:
754 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
755 .getTypePtr());
756
Douglas Gregor18857642009-04-30 17:32:17 +0000757 case Type::QualifiedName:
758 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
759
760 case Type::TemplateSpecialization:
761 assert(getCanonicalType(T) != T &&
762 "Cannot request the size of a dependent type");
763 // FIXME: this is likely to be wrong once we support template
764 // aliases, since a template alias could refer to a typedef that
765 // has an __aligned__ attribute on it.
766 return getTypeInfo(getCanonicalType(T));
767 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000768
Chris Lattner464175b2007-07-18 17:52:12 +0000769 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000770 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000771}
772
Chris Lattner34ebde42009-01-27 18:08:34 +0000773/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
774/// type for the current target in bits. This can be different than the ABI
775/// alignment in cases where it is beneficial for performance to overalign
776/// a data type.
777unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
778 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000779
780 // Double and long long should be naturally aligned if possible.
781 if (const ComplexType* CT = T->getAsComplexType())
782 T = CT->getElementType().getTypePtr();
783 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
784 T->isSpecificBuiltinType(BuiltinType::LongLong))
785 return std::max(ABIAlign, (unsigned)getTypeSize(T));
786
Chris Lattner34ebde42009-01-27 18:08:34 +0000787 return ABIAlign;
788}
789
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000790static void CollectLocalObjCIvars(ASTContext *Ctx,
791 const ObjCInterfaceDecl *OI,
792 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000793 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
794 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000795 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000796 if (!IVDecl->isInvalidDecl())
797 Fields.push_back(cast<FieldDecl>(IVDecl));
798 }
799}
800
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000801void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
802 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
803 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
804 CollectObjCIvars(SuperClass, Fields);
805 CollectLocalObjCIvars(this, OI, Fields);
806}
807
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000808/// ShallowCollectObjCIvars -
809/// Collect all ivars, including those synthesized, in the current class.
810///
811void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
812 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
813 bool CollectSynthesized) {
814 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
815 E = OI->ivar_end(); I != E; ++I) {
816 Ivars.push_back(*I);
817 }
818 if (CollectSynthesized)
819 CollectSynthesizedIvars(OI, Ivars);
820}
821
Fariborz Jahanian98200742009-05-12 18:14:29 +0000822void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
823 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000824 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
825 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000826 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
827 Ivars.push_back(Ivar);
828
829 // Also look into nested protocols.
830 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
831 E = PD->protocol_end(); P != E; ++P)
832 CollectProtocolSynthesizedIvars(*P, Ivars);
833}
834
835/// CollectSynthesizedIvars -
836/// This routine collect synthesized ivars for the designated class.
837///
838void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
839 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000840 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
841 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000842 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
843 Ivars.push_back(Ivar);
844 }
845 // Also look into interface's protocol list for properties declared
846 // in the protocol and whose ivars are synthesized.
847 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
848 PE = OI->protocol_end(); P != PE; ++P) {
849 ObjCProtocolDecl *PD = (*P);
850 CollectProtocolSynthesizedIvars(PD, Ivars);
851 }
852}
853
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000854unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
855 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000856 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
857 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000858 if ((*I)->getPropertyIvarDecl())
859 ++count;
860
861 // Also look into nested protocols.
862 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
863 E = PD->protocol_end(); P != E; ++P)
864 count += CountProtocolSynthesizedIvars(*P);
865 return count;
866}
867
868unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
869{
870 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000871 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
872 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000873 if ((*I)->getPropertyIvarDecl())
874 ++count;
875 }
876 // Also look into interface's protocol list for properties declared
877 // in the protocol and whose ivars are synthesized.
878 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
879 PE = OI->protocol_end(); P != PE; ++P) {
880 ObjCProtocolDecl *PD = (*P);
881 count += CountProtocolSynthesizedIvars(PD);
882 }
883 return count;
884}
885
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000886/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
887ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
888 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
889 I = ObjCImpls.find(D);
890 if (I != ObjCImpls.end())
891 return cast<ObjCImplementationDecl>(I->second);
892 return 0;
893}
894/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
895ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
896 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
897 I = ObjCImpls.find(D);
898 if (I != ObjCImpls.end())
899 return cast<ObjCCategoryImplDecl>(I->second);
900 return 0;
901}
902
903/// \brief Set the implementation of ObjCInterfaceDecl.
904void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
905 ObjCImplementationDecl *ImplD) {
906 assert(IFaceD && ImplD && "Passed null params");
907 ObjCImpls[IFaceD] = ImplD;
908}
909/// \brief Set the implementation of ObjCCategoryDecl.
910void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
911 ObjCCategoryImplDecl *ImplD) {
912 assert(CatD && ImplD && "Passed null params");
913 ObjCImpls[CatD] = ImplD;
914}
915
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000916/// \brief Allocate an uninitialized DeclaratorInfo.
917///
918/// The caller should initialize the memory held by DeclaratorInfo using
919/// the TypeLoc wrappers.
920///
921/// \param T the type that will be the basis for type source info. This type
922/// should refer to how the declarator was written in source code, not to
923/// what type semantic analysis resolved the declarator to.
924DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T) {
925 unsigned DataSize = TypeLoc::getFullDataSizeForType(T);
926 DeclaratorInfo *DInfo =
927 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
928 new (DInfo) DeclaratorInfo(T);
929 return DInfo;
930}
931
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000932/// getInterfaceLayoutImpl - Get or compute information about the
933/// layout of the given interface.
934///
935/// \param Impl - If given, also include the layout of the interface's
936/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000937const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000938ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
939 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000940 assert(!D->isForwardDecl() && "Invalid interface decl!");
941
Devang Patel44a3dde2008-06-04 21:54:36 +0000942 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000943 ObjCContainerDecl *Key =
944 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
945 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
946 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000947
Daniel Dunbar453addb2009-05-03 11:16:44 +0000948 // Add in synthesized ivar count if laying out an implementation.
949 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000950 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000951 unsigned SynthCount = CountSynthesizedIvars(D);
952 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000953 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000954 // entry. Note we can't cache this because we simply free all
955 // entries later; however we shouldn't look up implementations
956 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000957 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000958 return getObjCLayout(D, 0);
959 }
960
Anders Carlsson29445a02009-07-18 21:19:52 +0000961 const ASTRecordLayout *NewEntry =
962 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
963 ObjCLayouts[Key] = NewEntry;
964
Devang Patel44a3dde2008-06-04 21:54:36 +0000965 return *NewEntry;
966}
967
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000968const ASTRecordLayout &
969ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
970 return getObjCLayout(D, 0);
971}
972
973const ASTRecordLayout &
974ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
975 return getObjCLayout(D->getClassInterface(), D);
976}
977
Devang Patel88a981b2007-11-01 19:11:01 +0000978/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000979/// specified record (struct/union/class), which indicates its size and field
980/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000981const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000982 D = D->getDefinition(*this);
983 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000984
Chris Lattner464175b2007-07-18 17:52:12 +0000985 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +0000986 // Note that we can't save a reference to the entry because this function
987 // is recursive.
988 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000989 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000990
Anders Carlsson29445a02009-07-18 21:19:52 +0000991 const ASTRecordLayout *NewEntry =
992 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000993 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000994
Chris Lattner5d2a6302007-07-18 18:26:58 +0000995 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000996}
997
Chris Lattnera7674d82007-07-13 22:13:22 +0000998//===----------------------------------------------------------------------===//
999// Type creation/memoization methods
1000//===----------------------------------------------------------------------===//
1001
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001002QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001003 QualType CanT = getCanonicalType(T);
1004 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001005 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001006
1007 // If we are composing extended qualifiers together, merge together into one
1008 // ExtQualType node.
1009 unsigned CVRQuals = T.getCVRQualifiers();
1010 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1011 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001012
Chris Lattnerb7d25532009-02-18 22:53:11 +00001013 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1014 // If this type already has an address space specified, it cannot get
1015 // another one.
1016 assert(EQT->getAddressSpace() == 0 &&
1017 "Type cannot be in multiple addr spaces!");
1018 GCAttr = EQT->getObjCGCAttr();
1019 TypeNode = EQT->getBaseType();
1020 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001021
Chris Lattnerb7d25532009-02-18 22:53:11 +00001022 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001023 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001024 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001025 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001026 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001027 return QualType(EXTQy, CVRQuals);
1028
Christopher Lambebb97e92008-02-04 02:31:56 +00001029 // If the base type isn't canonical, this won't be a canonical type either,
1030 // so fill in the canonical type field.
1031 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001032 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001033 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001034
Chris Lattnerb7d25532009-02-18 22:53:11 +00001035 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001036 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001037 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001038 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001039 ExtQualType *New =
1040 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001041 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001042 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001043 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001044}
1045
Chris Lattnerb7d25532009-02-18 22:53:11 +00001046QualType ASTContext::getObjCGCQualType(QualType T,
1047 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001048 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001049 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001050 return T;
1051
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001052 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001053 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001054 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001055 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1056 return getPointerType(ResultType);
1057 }
1058 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001059 // If we are composing extended qualifiers together, merge together into one
1060 // ExtQualType node.
1061 unsigned CVRQuals = T.getCVRQualifiers();
1062 Type *TypeNode = T.getTypePtr();
1063 unsigned AddressSpace = 0;
1064
1065 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
Mike Stump24556362009-07-25 21:26:53 +00001066 // If this type already has an ObjCGC specified, it cannot get
Chris Lattnerb7d25532009-02-18 22:53:11 +00001067 // another one.
1068 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
Mike Stump24556362009-07-25 21:26:53 +00001069 "Type cannot have multiple ObjCGCs!");
Chris Lattnerb7d25532009-02-18 22:53:11 +00001070 AddressSpace = EQT->getAddressSpace();
1071 TypeNode = EQT->getBaseType();
1072 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001073
1074 // Check if we've already instantiated an gc qual'd type of this type.
1075 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001076 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001077 void *InsertPos = 0;
1078 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001079 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001080
1081 // If the base type isn't canonical, this won't be a canonical type either,
1082 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001083 // FIXME: Isn't this also not canonical if the base type is a array
1084 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001085 QualType Canonical;
1086 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001087 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001088
Chris Lattnerb7d25532009-02-18 22:53:11 +00001089 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001090 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1091 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1092 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001093 ExtQualType *New =
1094 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001095 ExtQualTypes.InsertNode(New, InsertPos);
1096 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001097 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001098}
Chris Lattnera7674d82007-07-13 22:13:22 +00001099
Mike Stump24556362009-07-25 21:26:53 +00001100QualType ASTContext::getNoReturnType(QualType T) {
Mike Stump6dcbc292009-07-25 23:24:03 +00001101 QualifierSet qs;
1102 qs.strip(T);
Mike Stump24556362009-07-25 21:26:53 +00001103 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001104 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001105 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001106 ResultType = getPointerType(ResultType);
1107 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1108 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001109 }
1110 if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001111 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001112 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001113 ResultType = getBlockPointerType(ResultType);
1114 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1115 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001116 }
1117 if (!T->isFunctionType())
1118 assert(0 && "can't noreturn qualify non-pointer to function or block type");
1119
Mike Stumpe24aea22009-07-27 22:25:19 +00001120 if (const FunctionNoProtoType *F = T->getAsFunctionNoProtoType()) {
Mike Stump24556362009-07-25 21:26:53 +00001121 return getFunctionNoProtoType(F->getResultType(), true);
1122 }
Mike Stumpe24aea22009-07-27 22:25:19 +00001123 const FunctionProtoType *F = T->getAsFunctionProtoType();
Mike Stump24556362009-07-25 21:26:53 +00001124 return getFunctionType(F->getResultType(), F->arg_type_begin(),
1125 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1126 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1127 F->getNumExceptions(), F->exception_begin(), true);
1128}
1129
Reid Spencer5f016e22007-07-11 17:01:13 +00001130/// getComplexType - Return the uniqued reference to the type for a complex
1131/// number with the specified element type.
1132QualType ASTContext::getComplexType(QualType T) {
1133 // Unique pointers, to guarantee there is only one pointer of a particular
1134 // structure.
1135 llvm::FoldingSetNodeID ID;
1136 ComplexType::Profile(ID, T);
1137
1138 void *InsertPos = 0;
1139 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1140 return QualType(CT, 0);
1141
1142 // If the pointee type isn't canonical, this won't be a canonical type either,
1143 // so fill in the canonical type field.
1144 QualType Canonical;
1145 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001146 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001147
1148 // Get the new insert position for the node we care about.
1149 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001150 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 }
Steve Narofff83820b2009-01-27 22:08:43 +00001152 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 Types.push_back(New);
1154 ComplexTypes.InsertNode(New, InsertPos);
1155 return QualType(New, 0);
1156}
1157
Eli Friedmanf98aba32009-02-13 02:31:07 +00001158QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1159 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1160 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1161 FixedWidthIntType *&Entry = Map[Width];
1162 if (!Entry)
1163 Entry = new FixedWidthIntType(Width, Signed);
1164 return QualType(Entry, 0);
1165}
Reid Spencer5f016e22007-07-11 17:01:13 +00001166
1167/// getPointerType - Return the uniqued reference to the type for a pointer to
1168/// the specified type.
1169QualType ASTContext::getPointerType(QualType T) {
1170 // Unique pointers, to guarantee there is only one pointer of a particular
1171 // structure.
1172 llvm::FoldingSetNodeID ID;
1173 PointerType::Profile(ID, T);
1174
1175 void *InsertPos = 0;
1176 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1177 return QualType(PT, 0);
1178
1179 // If the pointee type isn't canonical, this won't be a canonical type either,
1180 // so fill in the canonical type field.
1181 QualType Canonical;
1182 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001183 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001184
1185 // Get the new insert position for the node we care about.
1186 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001187 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 }
Steve Narofff83820b2009-01-27 22:08:43 +00001189 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 Types.push_back(New);
1191 PointerTypes.InsertNode(New, InsertPos);
1192 return QualType(New, 0);
1193}
1194
Steve Naroff5618bd42008-08-27 16:04:49 +00001195/// getBlockPointerType - Return the uniqued reference to the type for
1196/// a pointer to the specified block.
1197QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001198 assert(T->isFunctionType() && "block of function types only");
1199 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001200 // structure.
1201 llvm::FoldingSetNodeID ID;
1202 BlockPointerType::Profile(ID, T);
1203
1204 void *InsertPos = 0;
1205 if (BlockPointerType *PT =
1206 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1207 return QualType(PT, 0);
1208
Steve Naroff296e8d52008-08-28 19:20:44 +00001209 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001210 // type either so fill in the canonical type field.
1211 QualType Canonical;
1212 if (!T->isCanonical()) {
1213 Canonical = getBlockPointerType(getCanonicalType(T));
1214
1215 // Get the new insert position for the node we care about.
1216 BlockPointerType *NewIP =
1217 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001218 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001219 }
Steve Narofff83820b2009-01-27 22:08:43 +00001220 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001221 Types.push_back(New);
1222 BlockPointerTypes.InsertNode(New, InsertPos);
1223 return QualType(New, 0);
1224}
1225
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001226/// getLValueReferenceType - Return the uniqued reference to the type for an
1227/// lvalue reference to the specified type.
1228QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // Unique pointers, to guarantee there is only one pointer of a particular
1230 // structure.
1231 llvm::FoldingSetNodeID ID;
1232 ReferenceType::Profile(ID, T);
1233
1234 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001235 if (LValueReferenceType *RT =
1236 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // If the referencee type isn't canonical, this won't be a canonical type
1240 // either, so fill in the canonical type field.
1241 QualType Canonical;
1242 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001243 Canonical = getLValueReferenceType(getCanonicalType(T));
1244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001246 LValueReferenceType *NewIP =
1247 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001248 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 }
1250
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001251 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001253 LValueReferenceTypes.InsertNode(New, InsertPos);
1254 return QualType(New, 0);
1255}
1256
1257/// getRValueReferenceType - Return the uniqued reference to the type for an
1258/// rvalue reference to the specified type.
1259QualType ASTContext::getRValueReferenceType(QualType T) {
1260 // Unique pointers, to guarantee there is only one pointer of a particular
1261 // structure.
1262 llvm::FoldingSetNodeID ID;
1263 ReferenceType::Profile(ID, T);
1264
1265 void *InsertPos = 0;
1266 if (RValueReferenceType *RT =
1267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1268 return QualType(RT, 0);
1269
1270 // If the referencee type isn't canonical, this won't be a canonical type
1271 // either, so fill in the canonical type field.
1272 QualType Canonical;
1273 if (!T->isCanonical()) {
1274 Canonical = getRValueReferenceType(getCanonicalType(T));
1275
1276 // Get the new insert position for the node we care about.
1277 RValueReferenceType *NewIP =
1278 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1279 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1280 }
1281
1282 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1283 Types.push_back(New);
1284 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 return QualType(New, 0);
1286}
1287
Sebastian Redlf30208a2009-01-24 21:16:55 +00001288/// getMemberPointerType - Return the uniqued reference to the type for a
1289/// member pointer to the specified type, in the specified class.
1290QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1291{
1292 // Unique pointers, to guarantee there is only one pointer of a particular
1293 // structure.
1294 llvm::FoldingSetNodeID ID;
1295 MemberPointerType::Profile(ID, T, Cls);
1296
1297 void *InsertPos = 0;
1298 if (MemberPointerType *PT =
1299 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1300 return QualType(PT, 0);
1301
1302 // If the pointee or class type isn't canonical, this won't be a canonical
1303 // type either, so fill in the canonical type field.
1304 QualType Canonical;
1305 if (!T->isCanonical()) {
1306 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1307
1308 // Get the new insert position for the node we care about.
1309 MemberPointerType *NewIP =
1310 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1311 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1312 }
Steve Narofff83820b2009-01-27 22:08:43 +00001313 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001314 Types.push_back(New);
1315 MemberPointerTypes.InsertNode(New, InsertPos);
1316 return QualType(New, 0);
1317}
1318
Steve Narofffb22d962007-08-30 01:06:46 +00001319/// getConstantArrayType - Return the unique reference to the type for an
1320/// array of the specified element type.
1321QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001322 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001323 ArrayType::ArraySizeModifier ASM,
1324 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001325 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1326 "Constant array of VLAs is illegal!");
1327
Chris Lattner38aeec72009-05-13 04:12:56 +00001328 // Convert the array size into a canonical width matching the pointer size for
1329 // the target.
1330 llvm::APInt ArySize(ArySizeIn);
1331 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1332
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001334 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001335
1336 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001337 if (ConstantArrayType *ATP =
1338 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 return QualType(ATP, 0);
1340
1341 // If the element type isn't canonical, this won't be a canonical type either,
1342 // so fill in the canonical type field.
1343 QualType Canonical;
1344 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001345 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001346 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001348 ConstantArrayType *NewIP =
1349 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001350 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 }
1352
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001353 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001354 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001355 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 Types.push_back(New);
1357 return QualType(New, 0);
1358}
1359
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001360/// getConstantArrayWithExprType - Return a reference to the type for
1361/// an array of the specified element type.
1362QualType
1363ASTContext::getConstantArrayWithExprType(QualType EltTy,
1364 const llvm::APInt &ArySizeIn,
1365 Expr *ArySizeExpr,
1366 ArrayType::ArraySizeModifier ASM,
1367 unsigned EltTypeQuals,
1368 SourceRange Brackets) {
1369 // Convert the array size into a canonical width matching the pointer
1370 // size for the target.
1371 llvm::APInt ArySize(ArySizeIn);
1372 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1373
1374 // Compute the canonical ConstantArrayType.
1375 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1376 ArySize, ASM, EltTypeQuals);
1377 // Since we don't unique expressions, it isn't possible to unique VLA's
1378 // that have an expression provided for their size.
1379 ConstantArrayWithExprType *New =
1380 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1381 ArySize, ArySizeExpr,
1382 ASM, EltTypeQuals, Brackets);
1383 Types.push_back(New);
1384 return QualType(New, 0);
1385}
1386
1387/// getConstantArrayWithoutExprType - Return a reference to the type for
1388/// an array of the specified element type.
1389QualType
1390ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1391 const llvm::APInt &ArySizeIn,
1392 ArrayType::ArraySizeModifier ASM,
1393 unsigned EltTypeQuals) {
1394 // Convert the array size into a canonical width matching the pointer
1395 // size for the target.
1396 llvm::APInt ArySize(ArySizeIn);
1397 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1398
1399 // Compute the canonical ConstantArrayType.
1400 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1401 ArySize, ASM, EltTypeQuals);
1402 ConstantArrayWithoutExprType *New =
1403 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1404 ArySize, ASM, EltTypeQuals);
1405 Types.push_back(New);
1406 return QualType(New, 0);
1407}
1408
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001409/// getVariableArrayType - Returns a non-unique reference to the type for a
1410/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001411QualType ASTContext::getVariableArrayType(QualType EltTy,
1412 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001413 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001414 unsigned EltTypeQuals,
1415 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001416 // Since we don't unique expressions, it isn't possible to unique VLA's
1417 // that have an expression provided for their size.
1418
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001419 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001420 new(*this,8)VariableArrayType(EltTy, QualType(),
1421 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001422
1423 VariableArrayTypes.push_back(New);
1424 Types.push_back(New);
1425 return QualType(New, 0);
1426}
1427
Douglas Gregor898574e2008-12-05 23:32:09 +00001428/// getDependentSizedArrayType - Returns a non-unique reference to
1429/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001430/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001431QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1432 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001433 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001434 unsigned EltTypeQuals,
1435 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001436 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1437 "Size must be type- or value-dependent!");
1438
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001439 llvm::FoldingSetNodeID ID;
1440 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1441 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001442
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001443 void *InsertPos = 0;
1444 DependentSizedArrayType *Canon
1445 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1446 DependentSizedArrayType *New;
1447 if (Canon) {
1448 // We already have a canonical version of this array type; use it as
1449 // the canonical type for a newly-built type.
1450 New = new (*this,8) DependentSizedArrayType(*this, EltTy,
1451 QualType(Canon, 0),
1452 NumElts, ASM, EltTypeQuals,
1453 Brackets);
1454 } else {
1455 QualType CanonEltTy = getCanonicalType(EltTy);
1456 if (CanonEltTy == EltTy) {
1457 New = new (*this,8) DependentSizedArrayType(*this, EltTy, QualType(),
1458 NumElts, ASM, EltTypeQuals,
1459 Brackets);
1460 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1461 } else {
1462 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1463 ASM, EltTypeQuals,
1464 SourceRange());
1465 New = new (*this,8) DependentSizedArrayType(*this, EltTy, Canon,
1466 NumElts, ASM, EltTypeQuals,
1467 Brackets);
1468 }
1469 }
1470
Douglas Gregor898574e2008-12-05 23:32:09 +00001471 Types.push_back(New);
1472 return QualType(New, 0);
1473}
1474
Eli Friedmanc5773c42008-02-15 18:16:39 +00001475QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1476 ArrayType::ArraySizeModifier ASM,
1477 unsigned EltTypeQuals) {
1478 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001479 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001480
1481 void *InsertPos = 0;
1482 if (IncompleteArrayType *ATP =
1483 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1484 return QualType(ATP, 0);
1485
1486 // If the element type isn't canonical, this won't be a canonical type
1487 // either, so fill in the canonical type field.
1488 QualType Canonical;
1489
1490 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001491 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001492 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001493
1494 // Get the new insert position for the node we care about.
1495 IncompleteArrayType *NewIP =
1496 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001497 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001498 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001499
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001500 IncompleteArrayType *New
1501 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1502 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001503
1504 IncompleteArrayTypes.InsertNode(New, InsertPos);
1505 Types.push_back(New);
1506 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001507}
1508
Steve Naroff73322922007-07-18 18:00:27 +00001509/// getVectorType - Return the unique reference to a vector type of
1510/// the specified element type and size. VectorType must be a built-in type.
1511QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 BuiltinType *baseType;
1513
Chris Lattnerf52ab252008-04-06 22:59:24 +00001514 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001515 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001516
1517 // Check if we've already instantiated a vector of this type.
1518 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001519 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 void *InsertPos = 0;
1521 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1522 return QualType(VTP, 0);
1523
1524 // If the element type isn't canonical, this won't be a canonical type either,
1525 // so fill in the canonical type field.
1526 QualType Canonical;
1527 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001528 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001529
1530 // Get the new insert position for the node we care about.
1531 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001532 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 }
Steve Narofff83820b2009-01-27 22:08:43 +00001534 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 VectorTypes.InsertNode(New, InsertPos);
1536 Types.push_back(New);
1537 return QualType(New, 0);
1538}
1539
Nate Begeman213541a2008-04-18 23:10:10 +00001540/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001541/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001542QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001543 BuiltinType *baseType;
1544
Chris Lattnerf52ab252008-04-06 22:59:24 +00001545 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001546 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001547
1548 // Check if we've already instantiated a vector of this type.
1549 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001550 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001551 void *InsertPos = 0;
1552 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1553 return QualType(VTP, 0);
1554
1555 // If the element type isn't canonical, this won't be a canonical type either,
1556 // so fill in the canonical type field.
1557 QualType Canonical;
1558 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001559 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001560
1561 // Get the new insert position for the node we care about.
1562 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001563 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001564 }
Steve Narofff83820b2009-01-27 22:08:43 +00001565 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001566 VectorTypes.InsertNode(New, InsertPos);
1567 Types.push_back(New);
1568 return QualType(New, 0);
1569}
1570
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001571QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1572 Expr *SizeExpr,
1573 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001574 llvm::FoldingSetNodeID ID;
1575 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1576 SizeExpr);
1577
1578 void *InsertPos = 0;
1579 DependentSizedExtVectorType *Canon
1580 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1581 DependentSizedExtVectorType *New;
1582 if (Canon) {
1583 // We already have a canonical version of this array type; use it as
1584 // the canonical type for a newly-built type.
1585 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1586 QualType(Canon, 0),
1587 SizeExpr, AttrLoc);
1588 } else {
1589 QualType CanonVecTy = getCanonicalType(vecType);
1590 if (CanonVecTy == vecType) {
1591 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1592 QualType(), SizeExpr,
1593 AttrLoc);
1594 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1595 } else {
1596 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1597 SourceLocation());
1598 New = new (*this,8) DependentSizedExtVectorType(*this, vecType, Canon,
1599 SizeExpr, AttrLoc);
1600 }
1601 }
1602
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001603 Types.push_back(New);
1604 return QualType(New, 0);
1605}
1606
Douglas Gregor72564e72009-02-26 23:50:07 +00001607/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001608///
Mike Stump24556362009-07-25 21:26:53 +00001609QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // Unique functions, to guarantee there is only one function of a particular
1611 // structure.
1612 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001613 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001614
1615 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001616 if (FunctionNoProtoType *FT =
1617 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 return QualType(FT, 0);
1619
1620 QualType Canonical;
1621 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001622 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001623
1624 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 FunctionNoProtoType *NewIP =
1626 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001627 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 }
1629
Mike Stump24556362009-07-25 21:26:53 +00001630 FunctionNoProtoType *New
1631 = new (*this,8) FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001633 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 return QualType(New, 0);
1635}
1636
1637/// getFunctionType - Return a normal function type with a typed argument
1638/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001639QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001640 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001641 unsigned TypeQuals, bool hasExceptionSpec,
1642 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001643 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 // Unique functions, to guarantee there is only one function of a particular
1645 // structure.
1646 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001647 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001648 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001649 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001650
1651 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001652 if (FunctionProtoType *FTP =
1653 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001655
1656 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001658 if (hasExceptionSpec)
1659 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1661 if (!ArgArray[i]->isCanonical())
1662 isCanonical = false;
1663
1664 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001665 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 QualType Canonical;
1667 if (!isCanonical) {
1668 llvm::SmallVector<QualType, 16> CanonicalArgs;
1669 CanonicalArgs.reserve(NumArgs);
1670 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001671 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001672
Chris Lattnerf52ab252008-04-06 22:59:24 +00001673 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001674 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001675 isVariadic, TypeQuals, false,
1676 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001677
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001679 FunctionProtoType *NewIP =
1680 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001681 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001683
Douglas Gregor72564e72009-02-26 23:50:07 +00001684 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001685 // for two variable size arrays (for parameter and exception types) at the
1686 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001687 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001688 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1689 NumArgs*sizeof(QualType) +
1690 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001691 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001692 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001693 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 return QualType(FTP, 0);
1697}
1698
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001699/// getTypeDeclType - Return the unique reference to the type for the
1700/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001701QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001702 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001703 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1704
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001705 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001706 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001707 else if (isa<TemplateTypeParmDecl>(Decl)) {
1708 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001709 } else if (ObjCInterfaceDecl *ObjCInterface
1710 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001711 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001712
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001713 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001714 if (PrevDecl)
1715 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001716 else
1717 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001718 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001719 if (PrevDecl)
1720 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001721 else
1722 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001723 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001724 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001725
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001726 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001727 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001728}
1729
Reid Spencer5f016e22007-07-11 17:01:13 +00001730/// getTypedefType - Return the unique reference to the type for the
1731/// specified typename decl.
1732QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1733 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1734
Chris Lattnerf52ab252008-04-06 22:59:24 +00001735 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001736 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 Types.push_back(Decl->TypeForDecl);
1738 return QualType(Decl->TypeForDecl, 0);
1739}
1740
Douglas Gregorfab9d672009-02-05 23:33:38 +00001741/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001742/// parameter or parameter pack with the given depth, index, and (optionally)
1743/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001744QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001745 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001746 IdentifierInfo *Name) {
1747 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001748 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001749 void *InsertPos = 0;
1750 TemplateTypeParmType *TypeParm
1751 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1752
1753 if (TypeParm)
1754 return QualType(TypeParm, 0);
1755
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001756 if (Name) {
1757 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1758 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1759 Name, Canon);
1760 } else
1761 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001762
1763 Types.push_back(TypeParm);
1764 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1765
1766 return QualType(TypeParm, 0);
1767}
1768
Douglas Gregor55f6b142009-02-09 18:46:07 +00001769QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001770ASTContext::getTemplateSpecializationType(TemplateName Template,
1771 const TemplateArgument *Args,
1772 unsigned NumArgs,
1773 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001774 if (!Canon.isNull())
1775 Canon = getCanonicalType(Canon);
1776 else {
1777 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001778 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1779 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1780 CanonArgs.reserve(NumArgs);
1781 for (unsigned I = 0; I != NumArgs; ++I)
1782 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1783
1784 // Determine whether this canonical template specialization type already
1785 // exists.
1786 llvm::FoldingSetNodeID ID;
1787 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001788 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001789
1790 void *InsertPos = 0;
1791 TemplateSpecializationType *Spec
1792 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1793
1794 if (!Spec) {
1795 // Allocate a new canonical template specialization type.
1796 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1797 sizeof(TemplateArgument) * NumArgs),
1798 8);
Douglas Gregor828e2262009-07-29 16:09:57 +00001799 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001800 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001801 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001802 Types.push_back(Spec);
1803 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1804 }
1805
Douglas Gregorb88e8882009-07-30 17:40:51 +00001806 if (Canon.isNull())
1807 Canon = QualType(Spec, 0);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001808 assert(Canon->isDependentType() &&
1809 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001810 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001811
Douglas Gregor1275ae02009-07-28 23:00:59 +00001812 // Allocate the (non-canonical) template specialization type, but don't
1813 // try to unique it: these types typically have location information that
1814 // we don't unique and don't want to lose.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001815 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001816 sizeof(TemplateArgument) * NumArgs),
1817 8);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001818 TemplateSpecializationType *Spec
Douglas Gregor828e2262009-07-29 16:09:57 +00001819 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1820 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001821
Douglas Gregor55f6b142009-02-09 18:46:07 +00001822 Types.push_back(Spec);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001823 return QualType(Spec, 0);
1824}
1825
Douglas Gregore4e5b052009-03-19 00:18:19 +00001826QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001827ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001828 QualType NamedType) {
1829 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001830 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001831
1832 void *InsertPos = 0;
1833 QualifiedNameType *T
1834 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1835 if (T)
1836 return QualType(T, 0);
1837
Douglas Gregorab452ba2009-03-26 23:50:42 +00001838 T = new (*this) QualifiedNameType(NNS, NamedType,
1839 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001840 Types.push_back(T);
1841 QualifiedNameTypes.InsertNode(T, InsertPos);
1842 return QualType(T, 0);
1843}
1844
Douglas Gregord57959a2009-03-27 23:10:48 +00001845QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1846 const IdentifierInfo *Name,
1847 QualType Canon) {
1848 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1849
1850 if (Canon.isNull()) {
1851 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1852 if (CanonNNS != NNS)
1853 Canon = getTypenameType(CanonNNS, Name);
1854 }
1855
1856 llvm::FoldingSetNodeID ID;
1857 TypenameType::Profile(ID, NNS, Name);
1858
1859 void *InsertPos = 0;
1860 TypenameType *T
1861 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1862 if (T)
1863 return QualType(T, 0);
1864
1865 T = new (*this) TypenameType(NNS, Name, Canon);
1866 Types.push_back(T);
1867 TypenameTypes.InsertNode(T, InsertPos);
1868 return QualType(T, 0);
1869}
1870
Douglas Gregor17343172009-04-01 00:28:59 +00001871QualType
1872ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1873 const TemplateSpecializationType *TemplateId,
1874 QualType Canon) {
1875 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1876
1877 if (Canon.isNull()) {
1878 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1879 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1880 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1881 const TemplateSpecializationType *CanonTemplateId
1882 = CanonType->getAsTemplateSpecializationType();
1883 assert(CanonTemplateId &&
1884 "Canonical type must also be a template specialization type");
1885 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1886 }
1887 }
1888
1889 llvm::FoldingSetNodeID ID;
1890 TypenameType::Profile(ID, NNS, TemplateId);
1891
1892 void *InsertPos = 0;
1893 TypenameType *T
1894 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1895 if (T)
1896 return QualType(T, 0);
1897
1898 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1899 Types.push_back(T);
1900 TypenameTypes.InsertNode(T, InsertPos);
1901 return QualType(T, 0);
1902}
1903
Chris Lattner88cb27a2008-04-07 04:56:42 +00001904/// CmpProtocolNames - Comparison predicate for sorting protocols
1905/// alphabetically.
1906static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1907 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001908 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001909}
1910
1911static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1912 unsigned &NumProtocols) {
1913 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1914
1915 // Sort protocols, keyed by name.
1916 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1917
1918 // Remove duplicates.
1919 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1920 NumProtocols = ProtocolsEnd-Protocols;
1921}
1922
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001923/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1924/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001925QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001926 ObjCProtocolDecl **Protocols,
1927 unsigned NumProtocols) {
1928 // Sort the protocol list alphabetically to canonicalize it.
1929 if (NumProtocols)
1930 SortAndUniqueProtocols(Protocols, NumProtocols);
1931
1932 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001933 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001934
1935 void *InsertPos = 0;
1936 if (ObjCObjectPointerType *QT =
1937 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1938 return QualType(QT, 0);
1939
1940 // No Match;
1941 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001942 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001943
1944 Types.push_back(QType);
1945 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1946 return QualType(QType, 0);
1947}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001948
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001949/// getObjCInterfaceType - Return the unique reference to the type for the
1950/// specified ObjC interface decl. The list of protocols is optional.
1951QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001952 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001953 if (NumProtocols)
1954 // Sort the protocol list alphabetically to canonicalize it.
1955 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001956
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001957 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001958 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001959
1960 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001961 if (ObjCInterfaceType *QT =
1962 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001963 return QualType(QT, 0);
1964
1965 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001966 ObjCInterfaceType *QType =
1967 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1968 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001969 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001970 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001971 return QualType(QType, 0);
1972}
1973
Douglas Gregor72564e72009-02-26 23:50:07 +00001974/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1975/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001976/// multiple declarations that refer to "typeof(x)" all contain different
1977/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1978/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001979QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001980 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00001981 if (tofExpr->isTypeDependent()) {
1982 llvm::FoldingSetNodeID ID;
1983 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
1984
1985 void *InsertPos = 0;
1986 DependentTypeOfExprType *Canon
1987 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
1988 if (Canon) {
1989 // We already have a "canonical" version of an identical, dependent
1990 // typeof(expr) type. Use that as our canonical type.
1991 toe = new (*this, 8) TypeOfExprType(tofExpr,
1992 QualType((TypeOfExprType*)Canon, 0));
1993 }
1994 else {
1995 // Build a new, canonical typeof(expr) type.
1996 Canon = new (*this, 8) DependentTypeOfExprType(*this, tofExpr);
1997 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
1998 toe = Canon;
1999 }
2000 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002001 QualType Canonical = getCanonicalType(tofExpr->getType());
2002 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
2003 }
Steve Naroff9752f252007-08-01 18:02:17 +00002004 Types.push_back(toe);
2005 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002006}
2007
Steve Naroff9752f252007-08-01 18:02:17 +00002008/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2009/// TypeOfType AST's. The only motivation to unique these nodes would be
2010/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2011/// an issue. This doesn't effect the type checker, since it operates
2012/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002013QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002014 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00002015 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002016 Types.push_back(tot);
2017 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002018}
2019
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002020/// getDecltypeForExpr - Given an expr, will return the decltype for that
2021/// expression, according to the rules in C++0x [dcl.type.simple]p4
2022static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002023 if (e->isTypeDependent())
2024 return Context.DependentTy;
2025
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002026 // If e is an id expression or a class member access, decltype(e) is defined
2027 // as the type of the entity named by e.
2028 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2029 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2030 return VD->getType();
2031 }
2032 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2033 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2034 return FD->getType();
2035 }
2036 // If e is a function call or an invocation of an overloaded operator,
2037 // (parentheses around e are ignored), decltype(e) is defined as the
2038 // return type of that function.
2039 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2040 return CE->getCallReturnType();
2041
2042 QualType T = e->getType();
2043
2044 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2045 // defined as T&, otherwise decltype(e) is defined as T.
2046 if (e->isLvalue(Context) == Expr::LV_Valid)
2047 T = Context.getLValueReferenceType(T);
2048
2049 return T;
2050}
2051
Anders Carlsson395b4752009-06-24 19:06:50 +00002052/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2053/// DecltypeType AST's. The only motivation to unique these nodes would be
2054/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2055/// an issue. This doesn't effect the type checker, since it operates
2056/// on canonical type's (which are always unique).
2057QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002058 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002059 if (e->isTypeDependent()) {
2060 llvm::FoldingSetNodeID ID;
2061 DependentDecltypeType::Profile(ID, *this, e);
2062
2063 void *InsertPos = 0;
2064 DependentDecltypeType *Canon
2065 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2066 if (Canon) {
2067 // We already have a "canonical" version of an equivalent, dependent
2068 // decltype type. Use that as our canonical type.
2069 dt = new (*this, 8) DecltypeType(e, DependentTy,
2070 QualType((DecltypeType*)Canon, 0));
2071 }
2072 else {
2073 // Build a new, canonical typeof(expr) type.
2074 Canon = new (*this, 8) DependentDecltypeType(*this, e);
2075 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2076 dt = Canon;
2077 }
2078 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002079 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00002080 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002081 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002082 Types.push_back(dt);
2083 return QualType(dt, 0);
2084}
2085
Reid Spencer5f016e22007-07-11 17:01:13 +00002086/// getTagDeclType - Return the unique reference to the type for the
2087/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002088QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002089 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002090 // FIXME: What is the design on getTagDeclType when it requires casting
2091 // away const? mutable?
2092 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002093}
2094
2095/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2096/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2097/// needs to agree with the definition in <stddef.h>.
2098QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002099 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002100}
2101
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002102/// getSignedWCharType - Return the type of "signed wchar_t".
2103/// Used when in C++, as a GCC extension.
2104QualType ASTContext::getSignedWCharType() const {
2105 // FIXME: derive from "Target" ?
2106 return WCharTy;
2107}
2108
2109/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2110/// Used when in C++, as a GCC extension.
2111QualType ASTContext::getUnsignedWCharType() const {
2112 // FIXME: derive from "Target" ?
2113 return UnsignedIntTy;
2114}
2115
Chris Lattner8b9023b2007-07-13 03:05:23 +00002116/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2117/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2118QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002119 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002120}
2121
Chris Lattnere6327742008-04-02 05:18:44 +00002122//===----------------------------------------------------------------------===//
2123// Type Operators
2124//===----------------------------------------------------------------------===//
2125
Chris Lattner77c96472008-04-06 22:41:35 +00002126/// getCanonicalType - Return the canonical (structural) type corresponding to
2127/// the specified potentially non-canonical type. The non-canonical version
2128/// of a type may have many "decorated" versions of types. Decorators can
2129/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2130/// to be free of any of these, allowing two canonical types to be compared
2131/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002132CanQualType ASTContext::getCanonicalType(QualType T) {
Chris Lattner77c96472008-04-06 22:41:35 +00002133 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002134
2135 // If the result has type qualifiers, make sure to canonicalize them as well.
2136 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
Douglas Gregor50d62d12009-08-05 05:36:45 +00002137 if (TypeQuals == 0)
2138 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002139
2140 // If the type qualifiers are on an array type, get the canonical type of the
2141 // array with the qualifiers applied to the element type.
2142 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2143 if (!AT)
Douglas Gregor50d62d12009-08-05 05:36:45 +00002144 return CanQualType::CreateUnsafe(CanType.getQualifiedType(TypeQuals));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002145
2146 // Get the canonical version of the element with the extra qualifiers on it.
2147 // This can recursively sink qualifiers through multiple levels of arrays.
2148 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2149 NewEltTy = getCanonicalType(NewEltTy);
2150
2151 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002152 return CanQualType::CreateUnsafe(
2153 getConstantArrayType(NewEltTy, CAT->getSize(),
2154 CAT->getSizeModifier(),
2155 CAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002156 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002157 return CanQualType::CreateUnsafe(
2158 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2159 IAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002160
Douglas Gregor898574e2008-12-05 23:32:09 +00002161 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002162 return CanQualType::CreateUnsafe(
2163 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002164 DSAT->getSizeExpr() ?
2165 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002166 DSAT->getSizeModifier(),
2167 DSAT->getIndexTypeQualifier(),
2168 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002169
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002170 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002171 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002172 VAT->getSizeExpr() ?
2173 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002174 VAT->getSizeModifier(),
2175 VAT->getIndexTypeQualifier(),
2176 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002177}
2178
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002179TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2180 // If this template name refers to a template, the canonical
2181 // template name merely stores the template itself.
2182 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002183 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002184
Douglas Gregord99cbe62009-07-29 18:26:50 +00002185 // If this template name refers to a set of overloaded function templates,
2186 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002187 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2188 OverloadedFunctionDecl *CanonOvl = 0;
2189 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2190 FEnd = Ovl->function_end();
2191 F != FEnd; ++F) {
2192 Decl *Canon = F->get()->getCanonicalDecl();
2193 if (CanonOvl || Canon != F->get()) {
2194 if (!CanonOvl)
2195 CanonOvl = OverloadedFunctionDecl::Create(*this,
2196 Ovl->getDeclContext(),
2197 Ovl->getDeclName());
2198
2199 CanonOvl->addOverload(
2200 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2201 }
2202 }
2203
2204 return TemplateName(CanonOvl? CanonOvl : Ovl);
2205 }
Douglas Gregord99cbe62009-07-29 18:26:50 +00002206
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002207 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2208 assert(DTN && "Non-dependent template names must refer to template decls.");
2209 return DTN->CanonicalTemplateName;
2210}
2211
Douglas Gregor1275ae02009-07-28 23:00:59 +00002212TemplateArgument
2213ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2214 switch (Arg.getKind()) {
2215 case TemplateArgument::Null:
2216 return Arg;
2217
2218 case TemplateArgument::Expression:
2219 // FIXME: Build canonical expression?
2220 return Arg;
2221
2222 case TemplateArgument::Declaration:
2223 return TemplateArgument(SourceLocation(),
2224 Arg.getAsDecl()->getCanonicalDecl());
2225
2226 case TemplateArgument::Integral:
2227 return TemplateArgument(SourceLocation(),
2228 *Arg.getAsIntegral(),
2229 getCanonicalType(Arg.getIntegralType()));
2230
2231 case TemplateArgument::Type:
2232 return TemplateArgument(SourceLocation(),
2233 getCanonicalType(Arg.getAsType()));
2234
2235 case TemplateArgument::Pack: {
2236 // FIXME: Allocate in ASTContext
2237 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2238 unsigned Idx = 0;
2239 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2240 AEnd = Arg.pack_end();
2241 A != AEnd; (void)++A, ++Idx)
2242 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2243
2244 TemplateArgument Result;
2245 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2246 return Result;
2247 }
2248 }
2249
2250 // Silence GCC warning
2251 assert(false && "Unhandled template argument kind");
2252 return TemplateArgument();
2253}
2254
Douglas Gregord57959a2009-03-27 23:10:48 +00002255NestedNameSpecifier *
2256ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2257 if (!NNS)
2258 return 0;
2259
2260 switch (NNS->getKind()) {
2261 case NestedNameSpecifier::Identifier:
2262 // Canonicalize the prefix but keep the identifier the same.
2263 return NestedNameSpecifier::Create(*this,
2264 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2265 NNS->getAsIdentifier());
2266
2267 case NestedNameSpecifier::Namespace:
2268 // A namespace is canonical; build a nested-name-specifier with
2269 // this namespace and no prefix.
2270 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2271
2272 case NestedNameSpecifier::TypeSpec:
2273 case NestedNameSpecifier::TypeSpecWithTemplate: {
2274 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor495c35d2009-08-25 22:51:20 +00002275 return NestedNameSpecifier::Create(*this, 0,
Douglas Gregord57959a2009-03-27 23:10:48 +00002276 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2277 T.getTypePtr());
2278 }
2279
2280 case NestedNameSpecifier::Global:
2281 // The global specifier is canonical and unique.
2282 return NNS;
2283 }
2284
2285 // Required to silence a GCC warning
2286 return 0;
2287}
2288
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002289
2290const ArrayType *ASTContext::getAsArrayType(QualType T) {
2291 // Handle the non-qualified case efficiently.
2292 if (T.getCVRQualifiers() == 0) {
2293 // Handle the common positive case fast.
2294 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2295 return AT;
2296 }
2297
2298 // Handle the common negative case fast, ignoring CVR qualifiers.
2299 QualType CType = T->getCanonicalTypeInternal();
2300
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002301 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002302 // test.
2303 if (!isa<ArrayType>(CType) &&
2304 !isa<ArrayType>(CType.getUnqualifiedType()))
2305 return 0;
2306
2307 // Apply any CVR qualifiers from the array type to the element type. This
2308 // implements C99 6.7.3p8: "If the specification of an array type includes
2309 // any type qualifiers, the element type is so qualified, not the array type."
2310
2311 // If we get here, we either have type qualifiers on the type, or we have
2312 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002313 // we must propagate them down into the element type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002314 unsigned CVRQuals = T.getCVRQualifiers();
2315 unsigned AddrSpace = 0;
2316 Type *Ty = T.getTypePtr();
2317
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002318 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002319 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002320 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2321 AddrSpace = EXTQT->getAddressSpace();
2322 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002323 } else {
2324 T = Ty->getDesugaredType();
2325 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2326 break;
2327 CVRQuals |= T.getCVRQualifiers();
2328 Ty = T.getTypePtr();
2329 }
2330 }
2331
2332 // If we have a simple case, just return now.
2333 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2334 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2335 return ATy;
2336
2337 // Otherwise, we have an array and we have qualifiers on it. Push the
2338 // qualifiers into the array element type and return a new array type.
2339 // Get the canonical version of the element with the extra qualifiers on it.
2340 // This can recursively sink qualifiers through multiple levels of arrays.
2341 QualType NewEltTy = ATy->getElementType();
2342 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002343 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002344 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2345
2346 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2347 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2348 CAT->getSizeModifier(),
2349 CAT->getIndexTypeQualifier()));
2350 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2351 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2352 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002353 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002354
Douglas Gregor898574e2008-12-05 23:32:09 +00002355 if (const DependentSizedArrayType *DSAT
2356 = dyn_cast<DependentSizedArrayType>(ATy))
2357 return cast<ArrayType>(
2358 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002359 DSAT->getSizeExpr() ?
2360 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002361 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002362 DSAT->getIndexTypeQualifier(),
2363 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002364
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002365 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002366 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002367 VAT->getSizeExpr() ?
2368 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002369 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002370 VAT->getIndexTypeQualifier(),
2371 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002372}
2373
2374
Chris Lattnere6327742008-04-02 05:18:44 +00002375/// getArrayDecayedType - Return the properly qualified result of decaying the
2376/// specified array type to a pointer. This operation is non-trivial when
2377/// handling typedefs etc. The canonical type of "T" must be an array type,
2378/// this returns a pointer to a properly qualified element of the array.
2379///
2380/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2381QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002382 // Get the element type with 'getAsArrayType' so that we don't lose any
2383 // typedefs in the element type of the array. This also handles propagation
2384 // of type qualifiers from the array type into the element type if present
2385 // (C99 6.7.3p8).
2386 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2387 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002388
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002389 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002390
2391 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002392 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002393}
2394
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002395QualType ASTContext::getBaseElementType(QualType QT) {
2396 QualifierSet qualifiers;
2397 while (true) {
2398 const Type *UT = qualifiers.strip(QT);
2399 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2400 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002401 } else {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002402 return qualifiers.apply(QT, *this);
2403 }
2404 }
2405}
2406
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002407QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002408 QualType ElemTy = VAT->getElementType();
2409
2410 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2411 return getBaseElementType(VAT);
2412
2413 return ElemTy;
2414}
2415
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002416/// getConstantArrayElementCount - Returns number of constant array elements.
2417uint64_t
2418ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2419 uint64_t ElementCount = 1;
2420 do {
2421 ElementCount *= CA->getSize().getZExtValue();
2422 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2423 } while (CA);
2424 return ElementCount;
2425}
2426
Reid Spencer5f016e22007-07-11 17:01:13 +00002427/// getFloatingRank - Return a relative rank for floating point types.
2428/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002429static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002430 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002432
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002433 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002434 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002435 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002436 case BuiltinType::Float: return FloatRank;
2437 case BuiltinType::Double: return DoubleRank;
2438 case BuiltinType::LongDouble: return LongDoubleRank;
2439 }
2440}
2441
Steve Naroff716c7302007-08-27 01:41:48 +00002442/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2443/// point or a complex type (based on typeDomain/typeSize).
2444/// 'typeDomain' is a real floating point or complex type.
2445/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002446QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2447 QualType Domain) const {
2448 FloatingRank EltRank = getFloatingRank(Size);
2449 if (Domain->isComplexType()) {
2450 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002451 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002452 case FloatRank: return FloatComplexTy;
2453 case DoubleRank: return DoubleComplexTy;
2454 case LongDoubleRank: return LongDoubleComplexTy;
2455 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 }
Chris Lattner1361b112008-04-06 23:58:54 +00002457
2458 assert(Domain->isRealFloatingType() && "Unknown domain!");
2459 switch (EltRank) {
2460 default: assert(0 && "getFloatingRank(): illegal value for rank");
2461 case FloatRank: return FloatTy;
2462 case DoubleRank: return DoubleTy;
2463 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002464 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002465}
2466
Chris Lattner7cfeb082008-04-06 23:55:33 +00002467/// getFloatingTypeOrder - Compare the rank of the two specified floating
2468/// point types, ignoring the domain of the type (i.e. 'double' ==
2469/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2470/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002471int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2472 FloatingRank LHSR = getFloatingRank(LHS);
2473 FloatingRank RHSR = getFloatingRank(RHS);
2474
2475 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002476 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002477 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002478 return 1;
2479 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002480}
2481
Chris Lattnerf52ab252008-04-06 22:59:24 +00002482/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2483/// routine will assert if passed a built-in type that isn't an integer or enum,
2484/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002485unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002486 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002487 if (EnumType* ET = dyn_cast<EnumType>(T))
2488 T = ET->getDecl()->getIntegerType().getTypePtr();
2489
Eli Friedmana3426752009-07-05 23:44:27 +00002490 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2491 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2492
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002493 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2494 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2495
2496 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2497 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2498
Eli Friedmanf98aba32009-02-13 02:31:07 +00002499 // There are two things which impact the integer rank: the width, and
2500 // the ordering of builtins. The builtin ordering is encoded in the
2501 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002502 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002503 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002504
Chris Lattnerf52ab252008-04-06 22:59:24 +00002505 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002506 default: assert(0 && "getIntegerRank(): not a built-in integer");
2507 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002508 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002509 case BuiltinType::Char_S:
2510 case BuiltinType::Char_U:
2511 case BuiltinType::SChar:
2512 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002513 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002514 case BuiltinType::Short:
2515 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002516 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002517 case BuiltinType::Int:
2518 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002519 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002520 case BuiltinType::Long:
2521 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002522 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002523 case BuiltinType::LongLong:
2524 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002525 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002526 case BuiltinType::Int128:
2527 case BuiltinType::UInt128:
2528 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002529 }
2530}
2531
Eli Friedman04e83572009-08-20 04:21:42 +00002532/// \brief Whether this is a promotable bitfield reference according
2533/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2534///
2535/// \returns the type this bit-field will promote to, or NULL if no
2536/// promotion occurs.
2537QualType ASTContext::isPromotableBitField(Expr *E) {
2538 FieldDecl *Field = E->getBitField();
2539 if (!Field)
2540 return QualType();
2541
2542 QualType FT = Field->getType();
2543
2544 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2545 uint64_t BitWidth = BitWidthAP.getZExtValue();
2546 uint64_t IntSize = getTypeSize(IntTy);
2547 // GCC extension compatibility: if the bit-field size is less than or equal
2548 // to the size of int, it gets promoted no matter what its type is.
2549 // For instance, unsigned long bf : 4 gets promoted to signed int.
2550 if (BitWidth < IntSize)
2551 return IntTy;
2552
2553 if (BitWidth == IntSize)
2554 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2555
2556 // Types bigger than int are not subject to promotions, and therefore act
2557 // like the base type.
2558 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2559 // is ridiculous.
2560 return QualType();
2561}
2562
Eli Friedmana95d7572009-08-19 07:44:53 +00002563/// getPromotedIntegerType - Returns the type that Promotable will
2564/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2565/// integer type.
2566QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2567 assert(!Promotable.isNull());
2568 assert(Promotable->isPromotableIntegerType());
2569 if (Promotable->isSignedIntegerType())
2570 return IntTy;
2571 uint64_t PromotableSize = getTypeSize(Promotable);
2572 uint64_t IntSize = getTypeSize(IntTy);
2573 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2574 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2575}
2576
Chris Lattner7cfeb082008-04-06 23:55:33 +00002577/// getIntegerTypeOrder - Returns the highest ranked integer type:
2578/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2579/// LHS < RHS, return -1.
2580int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002581 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2582 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002583 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002584
Chris Lattnerf52ab252008-04-06 22:59:24 +00002585 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2586 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002587
Chris Lattner7cfeb082008-04-06 23:55:33 +00002588 unsigned LHSRank = getIntegerRank(LHSC);
2589 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002590
Chris Lattner7cfeb082008-04-06 23:55:33 +00002591 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2592 if (LHSRank == RHSRank) return 0;
2593 return LHSRank > RHSRank ? 1 : -1;
2594 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002595
Chris Lattner7cfeb082008-04-06 23:55:33 +00002596 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2597 if (LHSUnsigned) {
2598 // If the unsigned [LHS] type is larger, return it.
2599 if (LHSRank >= RHSRank)
2600 return 1;
2601
2602 // If the signed type can represent all values of the unsigned type, it
2603 // wins. Because we are dealing with 2's complement and types that are
2604 // powers of two larger than each other, this is always safe.
2605 return -1;
2606 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002607
Chris Lattner7cfeb082008-04-06 23:55:33 +00002608 // If the unsigned [RHS] type is larger, return it.
2609 if (RHSRank >= LHSRank)
2610 return -1;
2611
2612 // If the signed type can represent all values of the unsigned type, it
2613 // wins. Because we are dealing with 2's complement and types that are
2614 // powers of two larger than each other, this is always safe.
2615 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002616}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002617
2618// getCFConstantStringType - Return the type used for constant CFStrings.
2619QualType ASTContext::getCFConstantStringType() {
2620 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002621 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002622 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002623 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002624 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002625
2626 // const int *isa;
2627 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002628 // int flags;
2629 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002630 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002631 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002632 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002633 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002634
Anders Carlsson71993dd2007-08-17 05:31:46 +00002635 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002636 for (unsigned i = 0; i < 4; ++i) {
2637 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2638 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002639 FieldTypes[i], /*DInfo=*/0,
2640 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002641 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002642 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002643 }
2644
2645 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002646 }
2647
2648 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002649}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002650
Douglas Gregor319ac892009-04-23 22:29:11 +00002651void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002652 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002653 assert(Rec && "Invalid CFConstantStringType");
2654 CFConstantStringTypeDecl = Rec->getDecl();
2655}
2656
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002657QualType ASTContext::getObjCFastEnumerationStateType()
2658{
2659 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002660 ObjCFastEnumerationStateTypeDecl =
2661 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2662 &Idents.get("__objcFastEnumerationState"));
2663
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002664 QualType FieldTypes[] = {
2665 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002666 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002667 getPointerType(UnsignedLongTy),
2668 getConstantArrayType(UnsignedLongTy,
2669 llvm::APInt(32, 5), ArrayType::Normal, 0)
2670 };
2671
Douglas Gregor44b43212008-12-11 16:49:14 +00002672 for (size_t i = 0; i < 4; ++i) {
2673 FieldDecl *Field = FieldDecl::Create(*this,
2674 ObjCFastEnumerationStateTypeDecl,
2675 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002676 FieldTypes[i], /*DInfo=*/0,
2677 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002678 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002679 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002680 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002681
Douglas Gregor44b43212008-12-11 16:49:14 +00002682 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002683 }
2684
2685 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2686}
2687
Douglas Gregor319ac892009-04-23 22:29:11 +00002688void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002689 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002690 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2691 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2692}
2693
Anders Carlssone8c49532007-10-29 06:33:42 +00002694// This returns true if a type has been typedefed to BOOL:
2695// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002696static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002697 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002698 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2699 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002700
2701 return false;
2702}
2703
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002704/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002705/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002706int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002707 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002708
2709 // Make all integer and enum types at least as large as an int
2710 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002711 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002712 // Treat arrays as pointers, since that's how they're passed in.
2713 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002714 sz = getTypeSize(VoidPtrTy);
2715 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002716}
2717
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002718/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002719/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002720void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002721 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002722 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002723 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002724 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002725 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002726 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002727 // Compute size of all parameters.
2728 // Start with computing size of a pointer in number of bytes.
2729 // FIXME: There might(should) be a better way of doing this computation!
2730 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002731 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002732 // The first two arguments (self and _cmd) are pointers; account for
2733 // their size.
2734 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002735 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2736 E = Decl->param_end(); PI != E; ++PI) {
2737 QualType PType = (*PI)->getType();
2738 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002739 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002740 ParmOffset += sz;
2741 }
2742 S += llvm::utostr(ParmOffset);
2743 S += "@0:";
2744 S += llvm::utostr(PtrSize);
2745
2746 // Argument types.
2747 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002748 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2749 E = Decl->param_end(); PI != E; ++PI) {
2750 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002751 QualType PType = PVDecl->getOriginalType();
2752 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002753 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2754 // Use array's original type only if it has known number of
2755 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002756 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002757 PType = PVDecl->getType();
2758 } else if (PType->isFunctionType())
2759 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002760 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002761 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002762 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002763 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002764 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002765 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002766 }
2767}
2768
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002769/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002770/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002771/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2772/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002773/// Property attributes are stored as a comma-delimited C string. The simple
2774/// attributes readonly and bycopy are encoded as single characters. The
2775/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2776/// encoded as single characters, followed by an identifier. Property types
2777/// are also encoded as a parametrized attribute. The characters used to encode
2778/// these attributes are defined by the following enumeration:
2779/// @code
2780/// enum PropertyAttributes {
2781/// kPropertyReadOnly = 'R', // property is read-only.
2782/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2783/// kPropertyByref = '&', // property is a reference to the value last assigned
2784/// kPropertyDynamic = 'D', // property is dynamic
2785/// kPropertyGetter = 'G', // followed by getter selector name
2786/// kPropertySetter = 'S', // followed by setter selector name
2787/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2788/// kPropertyType = 't' // followed by old-style type encoding.
2789/// kPropertyWeak = 'W' // 'weak' property
2790/// kPropertyStrong = 'P' // property GC'able
2791/// kPropertyNonAtomic = 'N' // property non-atomic
2792/// };
2793/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002794void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2795 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002796 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002797 // Collect information from the property implementation decl(s).
2798 bool Dynamic = false;
2799 ObjCPropertyImplDecl *SynthesizePID = 0;
2800
2801 // FIXME: Duplicated code due to poor abstraction.
2802 if (Container) {
2803 if (const ObjCCategoryImplDecl *CID =
2804 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2805 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002806 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002807 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002808 ObjCPropertyImplDecl *PID = *i;
2809 if (PID->getPropertyDecl() == PD) {
2810 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2811 Dynamic = true;
2812 } else {
2813 SynthesizePID = PID;
2814 }
2815 }
2816 }
2817 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002818 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002819 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002820 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002821 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002822 ObjCPropertyImplDecl *PID = *i;
2823 if (PID->getPropertyDecl() == PD) {
2824 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2825 Dynamic = true;
2826 } else {
2827 SynthesizePID = PID;
2828 }
2829 }
2830 }
2831 }
2832 }
2833
2834 // FIXME: This is not very efficient.
2835 S = "T";
2836
2837 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002838 // GCC has some special rules regarding encoding of properties which
2839 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002840 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002841 true /* outermost type */,
2842 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002843
2844 if (PD->isReadOnly()) {
2845 S += ",R";
2846 } else {
2847 switch (PD->getSetterKind()) {
2848 case ObjCPropertyDecl::Assign: break;
2849 case ObjCPropertyDecl::Copy: S += ",C"; break;
2850 case ObjCPropertyDecl::Retain: S += ",&"; break;
2851 }
2852 }
2853
2854 // It really isn't clear at all what this means, since properties
2855 // are "dynamic by default".
2856 if (Dynamic)
2857 S += ",D";
2858
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002859 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2860 S += ",N";
2861
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002862 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2863 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002864 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002865 }
2866
2867 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2868 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002869 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002870 }
2871
2872 if (SynthesizePID) {
2873 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2874 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002875 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002876 }
2877
2878 // FIXME: OBJCGC: weak & strong
2879}
2880
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002881/// getLegacyIntegralTypeEncoding -
2882/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002883/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002884/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2885///
2886void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00002887 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002888 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002889 if (BT->getKind() == BuiltinType::ULong &&
2890 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002891 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002892 else
2893 if (BT->getKind() == BuiltinType::Long &&
2894 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002895 PointeeTy = IntTy;
2896 }
2897 }
2898}
2899
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002900void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002901 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002902 // We follow the behavior of gcc, expanding structures which are
2903 // directly pointed to, and expanding embedded structures. Note that
2904 // these rules are sufficient to prevent recursive encoding of the
2905 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002906 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2907 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002908}
2909
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002910static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002911 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002912 const Expr *E = FD->getBitWidth();
2913 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2914 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002915 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002916 S += 'b';
2917 S += llvm::utostr(N);
2918}
2919
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002920void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2921 bool ExpandPointedToStructures,
2922 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002923 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002924 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002925 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002926 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002927 if (FD && FD->isBitField())
2928 return EncodeBitField(this, S, FD);
2929 char encoding;
2930 switch (BT->getKind()) {
2931 default: assert(0 && "Unhandled builtin type kind");
2932 case BuiltinType::Void: encoding = 'v'; break;
2933 case BuiltinType::Bool: encoding = 'B'; break;
2934 case BuiltinType::Char_U:
2935 case BuiltinType::UChar: encoding = 'C'; break;
2936 case BuiltinType::UShort: encoding = 'S'; break;
2937 case BuiltinType::UInt: encoding = 'I'; break;
2938 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002939 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002940 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002941 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002942 case BuiltinType::UInt128: encoding = 'T'; break;
2943 case BuiltinType::ULongLong: encoding = 'Q'; break;
2944 case BuiltinType::Char_S:
2945 case BuiltinType::SChar: encoding = 'c'; break;
2946 case BuiltinType::Short: encoding = 's'; break;
2947 case BuiltinType::Int: encoding = 'i'; break;
2948 case BuiltinType::Long:
2949 encoding =
2950 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2951 break;
2952 case BuiltinType::LongLong: encoding = 'q'; break;
2953 case BuiltinType::Int128: encoding = 't'; break;
2954 case BuiltinType::Float: encoding = 'f'; break;
2955 case BuiltinType::Double: encoding = 'd'; break;
2956 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002957 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002958
2959 S += encoding;
2960 return;
2961 }
2962
2963 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002964 S += 'j';
2965 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2966 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002967 return;
2968 }
2969
Ted Kremenek6217b802009-07-29 21:53:49 +00002970 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002971 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002972 bool isReadOnly = false;
2973 // For historical/compatibility reasons, the read-only qualifier of the
2974 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2975 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2976 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00002977 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002978 if (OutermostType && T.isConstQualified()) {
2979 isReadOnly = true;
2980 S += 'r';
2981 }
Mike Stump9fdbab32009-07-31 02:02:20 +00002982 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002983 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002984 while (P->getAs<PointerType>())
2985 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002986 if (P.isConstQualified()) {
2987 isReadOnly = true;
2988 S += 'r';
2989 }
2990 }
2991 if (isReadOnly) {
2992 // Another legacy compatibility encoding. Some ObjC qualifier and type
2993 // combinations need to be rearranged.
2994 // Rewrite "in const" from "nr" to "rn"
2995 const char * s = S.c_str();
2996 int len = S.length();
2997 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2998 std::string replace = "rn";
2999 S.replace(S.end()-2, S.end(), replace);
3000 }
3001 }
Steve Naroff14108da2009-07-10 23:34:53 +00003002 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003003 S += ':';
3004 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003005 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003006
3007 if (PointeeTy->isCharType()) {
3008 // char pointer types should be encoded as '*' unless it is a
3009 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003010 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003011 S += '*';
3012 return;
3013 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003014 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003015 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3016 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3017 S += '#';
3018 return;
3019 }
3020 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3021 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3022 S += '@';
3023 return;
3024 }
3025 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003026 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003027 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003028 getLegacyIntegralTypeEncoding(PointeeTy);
3029
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003030 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003031 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003032 return;
3033 }
3034
3035 if (const ArrayType *AT =
3036 // Ignore type qualifiers etc.
3037 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003038 if (isa<IncompleteArrayType>(AT)) {
3039 // Incomplete arrays are encoded as a pointer to the array element.
3040 S += '^';
3041
3042 getObjCEncodingForTypeImpl(AT->getElementType(), S,
3043 false, ExpandStructures, FD);
3044 } else {
3045 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003046
Anders Carlsson559a8332009-02-22 01:38:57 +00003047 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3048 S += llvm::utostr(CAT->getSize().getZExtValue());
3049 else {
3050 //Variable length arrays are encoded as a regular array with 0 elements.
3051 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3052 S += '0';
3053 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003054
Anders Carlsson559a8332009-02-22 01:38:57 +00003055 getObjCEncodingForTypeImpl(AT->getElementType(), S,
3056 false, ExpandStructures, FD);
3057 S += ']';
3058 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003059 return;
3060 }
3061
3062 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003063 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003064 return;
3065 }
3066
Ted Kremenek6217b802009-07-29 21:53:49 +00003067 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003068 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003069 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003070 // Anonymous structures print as '?'
3071 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3072 S += II->getName();
3073 } else {
3074 S += '?';
3075 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003076 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003077 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003078 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3079 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003080 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003081 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003082 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003083 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003084 S += '"';
3085 }
3086
3087 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003088 if (Field->isBitField()) {
3089 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3090 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003091 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003092 QualType qt = Field->getType();
3093 getLegacyIntegralTypeEncoding(qt);
3094 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003095 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003096 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003097 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003098 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003099 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003100 return;
3101 }
3102
3103 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003104 if (FD && FD->isBitField())
3105 EncodeBitField(this, S, FD);
3106 else
3107 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003108 return;
3109 }
3110
3111 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003112 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003113 return;
3114 }
3115
3116 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003117 // @encode(class_name)
3118 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
3119 S += '{';
3120 const IdentifierInfo *II = OI->getIdentifier();
3121 S += II->getName();
3122 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003123 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003124 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003125 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003126 if (RecFields[i]->isBitField())
3127 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3128 RecFields[i]);
3129 else
3130 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3131 FD);
3132 }
3133 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003134 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003135 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003136
3137 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003138 if (OPT->isObjCIdType()) {
3139 S += '@';
3140 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003141 }
3142
3143 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003144 S += '#';
3145 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003146 }
3147
3148 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003149 getObjCEncodingForTypeImpl(getObjCIdType(), S,
3150 ExpandPointedToStructures,
3151 ExpandStructures, FD);
3152 if (FD || EncodingProperty) {
3153 // Note that we do extended encoding of protocol qualifer list
3154 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003155 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003156 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3157 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003158 S += '<';
3159 S += (*I)->getNameAsString();
3160 S += '>';
3161 }
3162 S += '"';
3163 }
3164 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003165 }
3166
3167 QualType PointeeTy = OPT->getPointeeType();
3168 if (!EncodingProperty &&
3169 isa<TypedefType>(PointeeTy.getTypePtr())) {
3170 // Another historical/compatibility reason.
3171 // We encode the underlying type which comes out as
3172 // {...};
3173 S += '^';
3174 getObjCEncodingForTypeImpl(PointeeTy, S,
3175 false, ExpandPointedToStructures,
3176 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003177 return;
3178 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003179
3180 S += '@';
3181 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003182 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003183 S += OPT->getInterfaceDecl()->getNameAsCString();
3184 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3185 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003186 S += '<';
3187 S += (*I)->getNameAsString();
3188 S += '>';
3189 }
3190 S += '"';
3191 }
3192 return;
3193 }
3194
3195 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003196}
3197
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003198void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003199 std::string& S) const {
3200 if (QT & Decl::OBJC_TQ_In)
3201 S += 'n';
3202 if (QT & Decl::OBJC_TQ_Inout)
3203 S += 'N';
3204 if (QT & Decl::OBJC_TQ_Out)
3205 S += 'o';
3206 if (QT & Decl::OBJC_TQ_Bycopy)
3207 S += 'O';
3208 if (QT & Decl::OBJC_TQ_Byref)
3209 S += 'R';
3210 if (QT & Decl::OBJC_TQ_Oneway)
3211 S += 'V';
3212}
3213
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003214void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003215 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3216
3217 BuiltinVaListType = T;
3218}
3219
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003220void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003221 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003222}
3223
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003224void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003225 ObjCSelType = T;
3226
3227 const TypedefType *TT = T->getAsTypedefType();
3228 if (!TT)
3229 return;
3230 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003231
3232 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003233 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003234 if (!ptr)
3235 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003236 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003237 if (!rec)
3238 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003239 SelStructType = rec;
3240}
3241
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003242void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003243 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003244}
3245
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003246void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003247 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003248}
3249
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003250void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3251 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003252 "'NSConstantString' type already set!");
3253
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003254 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003255}
3256
Douglas Gregor7532dc62009-03-30 22:58:21 +00003257/// \brief Retrieve the template name that represents a qualified
3258/// template name such as \c std::vector.
3259TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3260 bool TemplateKeyword,
3261 TemplateDecl *Template) {
3262 llvm::FoldingSetNodeID ID;
3263 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3264
3265 void *InsertPos = 0;
3266 QualifiedTemplateName *QTN =
3267 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3268 if (!QTN) {
3269 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3270 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3271 }
3272
3273 return TemplateName(QTN);
3274}
3275
Douglas Gregord99cbe62009-07-29 18:26:50 +00003276/// \brief Retrieve the template name that represents a qualified
3277/// template name such as \c std::vector.
3278TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3279 bool TemplateKeyword,
3280 OverloadedFunctionDecl *Template) {
3281 llvm::FoldingSetNodeID ID;
3282 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3283
3284 void *InsertPos = 0;
3285 QualifiedTemplateName *QTN =
3286 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3287 if (!QTN) {
3288 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3289 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3290 }
3291
3292 return TemplateName(QTN);
3293}
3294
Douglas Gregor7532dc62009-03-30 22:58:21 +00003295/// \brief Retrieve the template name that represents a dependent
3296/// template name such as \c MetaFun::template apply.
3297TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3298 const IdentifierInfo *Name) {
3299 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3300
3301 llvm::FoldingSetNodeID ID;
3302 DependentTemplateName::Profile(ID, NNS, Name);
3303
3304 void *InsertPos = 0;
3305 DependentTemplateName *QTN =
3306 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3307
3308 if (QTN)
3309 return TemplateName(QTN);
3310
3311 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3312 if (CanonNNS == NNS) {
3313 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3314 } else {
3315 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3316 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3317 }
3318
3319 DependentTemplateNames.InsertNode(QTN, InsertPos);
3320 return TemplateName(QTN);
3321}
3322
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003323/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003324/// TargetInfo, produce the corresponding type. The unsigned @p Type
3325/// is actually a value of type @c TargetInfo::IntType.
3326QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003327 switch (Type) {
3328 case TargetInfo::NoInt: return QualType();
3329 case TargetInfo::SignedShort: return ShortTy;
3330 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3331 case TargetInfo::SignedInt: return IntTy;
3332 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3333 case TargetInfo::SignedLong: return LongTy;
3334 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3335 case TargetInfo::SignedLongLong: return LongLongTy;
3336 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3337 }
3338
3339 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003340 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003341}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003342
3343//===----------------------------------------------------------------------===//
3344// Type Predicates.
3345//===----------------------------------------------------------------------===//
3346
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003347/// isObjCNSObjectType - Return true if this is an NSObject object using
3348/// NSObject attribute on a c-style pointer type.
3349/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003350/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003351///
3352bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3353 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3354 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003355 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003356 return true;
3357 }
3358 return false;
3359}
3360
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003361/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3362/// garbage collection attribute.
3363///
3364QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003365 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003366 if (getLangOptions().ObjC1 &&
3367 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003368 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003369 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003370 // (or pointers to them) be treated as though they were declared
3371 // as __strong.
3372 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003373 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003374 GCAttrs = QualType::Strong;
3375 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003376 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003377 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003378 // Non-pointers have none gc'able attribute regardless of the attribute
3379 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003380 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003381 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003382 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003383 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003384}
3385
Chris Lattner6ac46a42008-04-07 06:51:04 +00003386//===----------------------------------------------------------------------===//
3387// Type Compatibility Testing
3388//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003389
Chris Lattner6ac46a42008-04-07 06:51:04 +00003390/// areCompatVectorTypes - Return true if the two specified vector types are
3391/// compatible.
3392static bool areCompatVectorTypes(const VectorType *LHS,
3393 const VectorType *RHS) {
3394 assert(LHS->isCanonical() && RHS->isCanonical());
3395 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003396 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003397}
3398
Steve Naroff4084c302009-07-23 01:01:38 +00003399//===----------------------------------------------------------------------===//
3400// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3401//===----------------------------------------------------------------------===//
3402
3403/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3404/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003405bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3406 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003407 if (lProto == rProto)
3408 return true;
3409 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3410 E = rProto->protocol_end(); PI != E; ++PI)
3411 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3412 return true;
3413 return false;
3414}
3415
Steve Naroff4084c302009-07-23 01:01:38 +00003416/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3417/// return true if lhs's protocols conform to rhs's protocol; false
3418/// otherwise.
3419bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3420 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3421 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3422 return false;
3423}
3424
3425/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3426/// ObjCQualifiedIDType.
3427bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3428 bool compare) {
3429 // Allow id<P..> and an 'id' or void* type in all cases.
3430 if (lhs->isVoidPointerType() ||
3431 lhs->isObjCIdType() || lhs->isObjCClassType())
3432 return true;
3433 else if (rhs->isVoidPointerType() ||
3434 rhs->isObjCIdType() || rhs->isObjCClassType())
3435 return true;
3436
3437 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3438 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3439
3440 if (!rhsOPT) return false;
3441
3442 if (rhsOPT->qual_empty()) {
3443 // If the RHS is a unqualified interface pointer "NSString*",
3444 // make sure we check the class hierarchy.
3445 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3446 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3447 E = lhsQID->qual_end(); I != E; ++I) {
3448 // when comparing an id<P> on lhs with a static type on rhs,
3449 // see if static class implements all of id's protocols, directly or
3450 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003451 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003452 return false;
3453 }
3454 }
3455 // If there are no qualifiers and no interface, we have an 'id'.
3456 return true;
3457 }
3458 // Both the right and left sides have qualifiers.
3459 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3460 E = lhsQID->qual_end(); I != E; ++I) {
3461 ObjCProtocolDecl *lhsProto = *I;
3462 bool match = false;
3463
3464 // when comparing an id<P> on lhs with a static type on rhs,
3465 // see if static class implements all of id's protocols, directly or
3466 // through its super class and categories.
3467 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3468 E = rhsOPT->qual_end(); J != E; ++J) {
3469 ObjCProtocolDecl *rhsProto = *J;
3470 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3471 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3472 match = true;
3473 break;
3474 }
3475 }
3476 // If the RHS is a qualified interface pointer "NSString<P>*",
3477 // make sure we check the class hierarchy.
3478 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3479 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3480 E = lhsQID->qual_end(); I != E; ++I) {
3481 // when comparing an id<P> on lhs with a static type on rhs,
3482 // see if static class implements all of id's protocols, directly or
3483 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003484 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003485 match = true;
3486 break;
3487 }
3488 }
3489 }
3490 if (!match)
3491 return false;
3492 }
3493
3494 return true;
3495 }
3496
3497 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3498 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3499
3500 if (const ObjCObjectPointerType *lhsOPT =
3501 lhs->getAsObjCInterfacePointerType()) {
3502 if (lhsOPT->qual_empty()) {
3503 bool match = false;
3504 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3505 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3506 E = rhsQID->qual_end(); I != E; ++I) {
3507 // when comparing an id<P> on lhs with a static type on rhs,
3508 // see if static class implements all of id's protocols, directly or
3509 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003510 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003511 match = true;
3512 break;
3513 }
3514 }
3515 if (!match)
3516 return false;
3517 }
3518 return true;
3519 }
3520 // Both the right and left sides have qualifiers.
3521 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3522 E = lhsOPT->qual_end(); I != E; ++I) {
3523 ObjCProtocolDecl *lhsProto = *I;
3524 bool match = false;
3525
3526 // when comparing an id<P> on lhs with a static type on rhs,
3527 // see if static class implements all of id's protocols, directly or
3528 // through its super class and categories.
3529 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3530 E = rhsQID->qual_end(); J != E; ++J) {
3531 ObjCProtocolDecl *rhsProto = *J;
3532 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3533 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3534 match = true;
3535 break;
3536 }
3537 }
3538 if (!match)
3539 return false;
3540 }
3541 return true;
3542 }
3543 return false;
3544}
3545
Eli Friedman3d815e72008-08-22 00:56:42 +00003546/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003547/// compatible for assignment from RHS to LHS. This handles validation of any
3548/// protocol qualifiers on the LHS or RHS.
3549///
Steve Naroff14108da2009-07-10 23:34:53 +00003550bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3551 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003552 // If either type represents the built-in 'id' or 'Class' types, return true.
3553 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003554 return true;
3555
Steve Naroff4084c302009-07-23 01:01:38 +00003556 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3557 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3558 QualType(RHSOPT,0),
3559 false);
3560
Steve Naroff14108da2009-07-10 23:34:53 +00003561 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3562 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003563 if (LHS && RHS) // We have 2 user-defined types.
3564 return canAssignObjCInterfaces(LHS, RHS);
3565
3566 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003567}
3568
Eli Friedman3d815e72008-08-22 00:56:42 +00003569bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3570 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003571 // Verify that the base decls are compatible: the RHS must be a subclass of
3572 // the LHS.
3573 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3574 return false;
3575
3576 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3577 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003578 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003579 return true;
3580
3581 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3582 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003583 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003584 return true; // FIXME: should return false!
3585
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003586 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3587 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003588 LHSPI != LHSPE; LHSPI++) {
3589 bool RHSImplementsProtocol = false;
3590
3591 // If the RHS doesn't implement the protocol on the left, the types
3592 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003593 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003594 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003595 RHSPI != RHSPE; RHSPI++) {
3596 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003597 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003598 break;
3599 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003600 }
3601 // FIXME: For better diagnostics, consider passing back the protocol name.
3602 if (!RHSImplementsProtocol)
3603 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003604 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003605 // The RHS implements all protocols listed on the LHS.
3606 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003607}
3608
Steve Naroff389bf462009-02-12 17:52:19 +00003609bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3610 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003611 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3612 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003613
Steve Naroff14108da2009-07-10 23:34:53 +00003614 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003615 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003616
3617 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3618 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003619}
3620
Steve Naroffec0550f2007-10-15 20:41:53 +00003621/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3622/// both shall have the identically qualified version of a compatible type.
3623/// C99 6.2.7p1: Two types have compatible types if their types are the
3624/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003625bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3626 return !mergeTypes(LHS, RHS).isNull();
3627}
3628
3629QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3630 const FunctionType *lbase = lhs->getAsFunctionType();
3631 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003632 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3633 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003634 bool allLTypes = true;
3635 bool allRTypes = true;
3636
3637 // Check return type
3638 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3639 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003640 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3641 allLTypes = false;
3642 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3643 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003644 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003645 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3646 if (NoReturn != lbase->getNoReturnAttr())
3647 allLTypes = false;
3648 if (NoReturn != rbase->getNoReturnAttr())
3649 allRTypes = false;
3650
Eli Friedman3d815e72008-08-22 00:56:42 +00003651 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003652 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3653 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003654 unsigned lproto_nargs = lproto->getNumArgs();
3655 unsigned rproto_nargs = rproto->getNumArgs();
3656
3657 // Compatible functions must have the same number of arguments
3658 if (lproto_nargs != rproto_nargs)
3659 return QualType();
3660
3661 // Variadic and non-variadic functions aren't compatible
3662 if (lproto->isVariadic() != rproto->isVariadic())
3663 return QualType();
3664
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003665 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3666 return QualType();
3667
Eli Friedman3d815e72008-08-22 00:56:42 +00003668 // Check argument compatibility
3669 llvm::SmallVector<QualType, 10> types;
3670 for (unsigned i = 0; i < lproto_nargs; i++) {
3671 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3672 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3673 QualType argtype = mergeTypes(largtype, rargtype);
3674 if (argtype.isNull()) return QualType();
3675 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003676 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3677 allLTypes = false;
3678 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3679 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003680 }
3681 if (allLTypes) return lhs;
3682 if (allRTypes) return rhs;
3683 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003684 lproto->isVariadic(), lproto->getTypeQuals(),
3685 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003686 }
3687
3688 if (lproto) allRTypes = false;
3689 if (rproto) allLTypes = false;
3690
Douglas Gregor72564e72009-02-26 23:50:07 +00003691 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003692 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003693 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003694 if (proto->isVariadic()) return QualType();
3695 // Check that the types are compatible with the types that
3696 // would result from default argument promotions (C99 6.7.5.3p15).
3697 // The only types actually affected are promotable integer
3698 // types and floats, which would be passed as a different
3699 // type depending on whether the prototype is visible.
3700 unsigned proto_nargs = proto->getNumArgs();
3701 for (unsigned i = 0; i < proto_nargs; ++i) {
3702 QualType argTy = proto->getArgType(i);
3703 if (argTy->isPromotableIntegerType() ||
3704 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3705 return QualType();
3706 }
3707
3708 if (allLTypes) return lhs;
3709 if (allRTypes) return rhs;
3710 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003711 proto->getNumArgs(), proto->isVariadic(),
3712 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003713 }
3714
3715 if (allLTypes) return lhs;
3716 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003717 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003718}
3719
3720QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003721 // C++ [expr]: If an expression initially has the type "reference to T", the
3722 // type is adjusted to "T" prior to any further analysis, the expression
3723 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003724 // expression is an lvalue unless the reference is an rvalue reference and
3725 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003726 // FIXME: C++ shouldn't be going through here! The rules are different
3727 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003728 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3729 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003730 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003731 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003732 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003733 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003734
Eli Friedman3d815e72008-08-22 00:56:42 +00003735 QualType LHSCan = getCanonicalType(LHS),
3736 RHSCan = getCanonicalType(RHS);
3737
3738 // If two types are identical, they are compatible.
3739 if (LHSCan == RHSCan)
3740 return LHS;
3741
3742 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003743 // Note that we handle extended qualifiers later, in the
3744 // case for ExtQualType.
3745 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003746 return QualType();
3747
Eli Friedman852d63b2009-06-01 01:22:52 +00003748 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3749 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003750
Chris Lattner1adb8832008-01-14 05:45:46 +00003751 // We want to consider the two function types to be the same for these
3752 // comparisons, just force one to the other.
3753 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3754 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003755
Eli Friedman07d25872009-06-02 05:28:56 +00003756 // Strip off objc_gc attributes off the top level so they can be merged.
3757 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003758 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003759 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3760 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003761 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003762 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003763 // __strong attribue is redundant if other decl is an objective-c
3764 // object pointer (or decorated with __strong attribute); otherwise
3765 // issue error.
3766 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3767 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003768 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003769 return QualType();
3770
Eli Friedman07d25872009-06-02 05:28:56 +00003771 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3772 RHS.getCVRQualifiers());
3773 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003774 if (!Result.isNull()) {
3775 if (Result.getObjCGCAttr() == QualType::GCNone)
3776 Result = getObjCGCQualType(Result, GCAttr);
3777 else if (Result.getObjCGCAttr() != GCAttr)
3778 Result = QualType();
3779 }
Eli Friedman07d25872009-06-02 05:28:56 +00003780 return Result;
3781 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003782 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003783 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003784 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3785 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003786 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3787 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003788 // __strong attribue is redundant if other decl is an objective-c
3789 // object pointer (or decorated with __strong attribute); otherwise
3790 // issue error.
3791 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3792 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003793 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003794 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003795
Eli Friedman07d25872009-06-02 05:28:56 +00003796 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3797 LHS.getCVRQualifiers());
3798 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003799 if (!Result.isNull()) {
3800 if (Result.getObjCGCAttr() == QualType::GCNone)
3801 Result = getObjCGCQualType(Result, GCAttr);
3802 else if (Result.getObjCGCAttr() != GCAttr)
3803 Result = QualType();
3804 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003805 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003806 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003807 }
3808
Eli Friedman4c721d32008-02-12 08:23:06 +00003809 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003810 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3811 LHSClass = Type::ConstantArray;
3812 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3813 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003814
Nate Begeman213541a2008-04-18 23:10:10 +00003815 // Canonicalize ExtVector -> Vector.
3816 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3817 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003818
3819 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003820 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003821 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3822 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003823 if (const EnumType* ETy = LHS->getAsEnumType()) {
3824 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3825 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003826 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003827 if (const EnumType* ETy = RHS->getAsEnumType()) {
3828 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3829 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003830 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003831
Eli Friedman3d815e72008-08-22 00:56:42 +00003832 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003833 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003834
Steve Naroff4a746782008-01-09 22:43:08 +00003835 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003836 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003837#define TYPE(Class, Base)
3838#define ABSTRACT_TYPE(Class, Base)
3839#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3840#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3841#include "clang/AST/TypeNodes.def"
3842 assert(false && "Non-canonical and dependent types shouldn't get here");
3843 return QualType();
3844
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003845 case Type::LValueReference:
3846 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003847 case Type::MemberPointer:
3848 assert(false && "C++ should never be in mergeTypes");
3849 return QualType();
3850
3851 case Type::IncompleteArray:
3852 case Type::VariableArray:
3853 case Type::FunctionProto:
3854 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003855 assert(false && "Types are eliminated above");
3856 return QualType();
3857
Chris Lattner1adb8832008-01-14 05:45:46 +00003858 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003859 {
3860 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003861 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
3862 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003863 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3864 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003865 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003866 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003867 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003868 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003869 return getPointerType(ResultType);
3870 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003871 case Type::BlockPointer:
3872 {
3873 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003874 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
3875 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003876 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3877 if (ResultType.isNull()) return QualType();
3878 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3879 return LHS;
3880 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3881 return RHS;
3882 return getBlockPointerType(ResultType);
3883 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003884 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003885 {
3886 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3887 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3888 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3889 return QualType();
3890
3891 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3892 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3893 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3894 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003895 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3896 return LHS;
3897 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3898 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003899 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3900 ArrayType::ArraySizeModifier(), 0);
3901 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3902 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003903 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3904 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003905 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3906 return LHS;
3907 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3908 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003909 if (LVAT) {
3910 // FIXME: This isn't correct! But tricky to implement because
3911 // the array's size has to be the size of LHS, but the type
3912 // has to be different.
3913 return LHS;
3914 }
3915 if (RVAT) {
3916 // FIXME: This isn't correct! But tricky to implement because
3917 // the array's size has to be the size of RHS, but the type
3918 // has to be different.
3919 return RHS;
3920 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003921 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3922 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003923 return getIncompleteArrayType(ResultType,
3924 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003925 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003926 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003927 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003928 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003929 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003930 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003931 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003932 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003933 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003934 case Type::Complex:
3935 // Distinct complex types are incompatible.
3936 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003937 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003938 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003939 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3940 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003941 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003942 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003943 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003944 // FIXME: This should be type compatibility, e.g. whether
3945 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003946 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3947 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3948 if (LHSIface && RHSIface &&
3949 canAssignObjCInterfaces(LHSIface, RHSIface))
3950 return LHS;
3951
Eli Friedman3d815e72008-08-22 00:56:42 +00003952 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003953 }
Steve Naroff14108da2009-07-10 23:34:53 +00003954 case Type::ObjCObjectPointer: {
Steve Naroff14108da2009-07-10 23:34:53 +00003955 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3956 RHS->getAsObjCObjectPointerType()))
3957 return LHS;
3958
Steve Naroffbc76dd02008-12-10 22:14:21 +00003959 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003960 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003961 case Type::FixedWidthInt:
3962 // Distinct fixed-width integers are not compatible.
3963 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003964 case Type::ExtQual:
3965 // FIXME: ExtQual types can be compatible even if they're not
3966 // identical!
3967 return QualType();
3968 // First attempt at an implementation, but I'm not really sure it's
3969 // right...
3970#if 0
3971 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3972 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3973 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3974 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3975 return QualType();
3976 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3977 LHSBase = QualType(LQual->getBaseType(), 0);
3978 RHSBase = QualType(RQual->getBaseType(), 0);
3979 ResultType = mergeTypes(LHSBase, RHSBase);
3980 if (ResultType.isNull()) return QualType();
3981 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3982 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3983 return LHS;
3984 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3985 return RHS;
3986 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3987 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3988 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3989 return ResultType;
3990#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003991
3992 case Type::TemplateSpecialization:
3993 assert(false && "Dependent types have no size");
3994 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003995 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003996
3997 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003998}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003999
Chris Lattner5426bf62008-04-07 07:01:58 +00004000//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004001// Integer Predicates
4002//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004003
Eli Friedmanad74a752008-06-28 06:23:08 +00004004unsigned ASTContext::getIntWidth(QualType T) {
4005 if (T == BoolTy)
4006 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00004007 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
4008 return FWIT->getWidth();
4009 }
4010 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004011 return (unsigned)getTypeSize(T);
4012}
4013
4014QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4015 assert(T->isSignedIntegerType() && "Unexpected type");
4016 if (const EnumType* ETy = T->getAsEnumType())
4017 T = ETy->getDecl()->getIntegerType();
4018 const BuiltinType* BTy = T->getAsBuiltinType();
4019 assert (BTy && "Unexpected signed integer type");
4020 switch (BTy->getKind()) {
4021 case BuiltinType::Char_S:
4022 case BuiltinType::SChar:
4023 return UnsignedCharTy;
4024 case BuiltinType::Short:
4025 return UnsignedShortTy;
4026 case BuiltinType::Int:
4027 return UnsignedIntTy;
4028 case BuiltinType::Long:
4029 return UnsignedLongTy;
4030 case BuiltinType::LongLong:
4031 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004032 case BuiltinType::Int128:
4033 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004034 default:
4035 assert(0 && "Unexpected signed integer type");
4036 return QualType();
4037 }
4038}
4039
Douglas Gregor2cf26342009-04-09 22:27:44 +00004040ExternalASTSource::~ExternalASTSource() { }
4041
4042void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004043
4044
4045//===----------------------------------------------------------------------===//
4046// Builtin Type Computation
4047//===----------------------------------------------------------------------===//
4048
4049/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4050/// pointer over the consumed characters. This returns the resultant type.
4051static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4052 ASTContext::GetBuiltinTypeError &Error,
4053 bool AllowTypeModifiers = true) {
4054 // Modifiers.
4055 int HowLong = 0;
4056 bool Signed = false, Unsigned = false;
4057
4058 // Read the modifiers first.
4059 bool Done = false;
4060 while (!Done) {
4061 switch (*Str++) {
4062 default: Done = true; --Str; break;
4063 case 'S':
4064 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4065 assert(!Signed && "Can't use 'S' modifier multiple times!");
4066 Signed = true;
4067 break;
4068 case 'U':
4069 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4070 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4071 Unsigned = true;
4072 break;
4073 case 'L':
4074 assert(HowLong <= 2 && "Can't have LLLL modifier");
4075 ++HowLong;
4076 break;
4077 }
4078 }
4079
4080 QualType Type;
4081
4082 // Read the base type.
4083 switch (*Str++) {
4084 default: assert(0 && "Unknown builtin type letter!");
4085 case 'v':
4086 assert(HowLong == 0 && !Signed && !Unsigned &&
4087 "Bad modifiers used with 'v'!");
4088 Type = Context.VoidTy;
4089 break;
4090 case 'f':
4091 assert(HowLong == 0 && !Signed && !Unsigned &&
4092 "Bad modifiers used with 'f'!");
4093 Type = Context.FloatTy;
4094 break;
4095 case 'd':
4096 assert(HowLong < 2 && !Signed && !Unsigned &&
4097 "Bad modifiers used with 'd'!");
4098 if (HowLong)
4099 Type = Context.LongDoubleTy;
4100 else
4101 Type = Context.DoubleTy;
4102 break;
4103 case 's':
4104 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4105 if (Unsigned)
4106 Type = Context.UnsignedShortTy;
4107 else
4108 Type = Context.ShortTy;
4109 break;
4110 case 'i':
4111 if (HowLong == 3)
4112 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4113 else if (HowLong == 2)
4114 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4115 else if (HowLong == 1)
4116 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4117 else
4118 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4119 break;
4120 case 'c':
4121 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4122 if (Signed)
4123 Type = Context.SignedCharTy;
4124 else if (Unsigned)
4125 Type = Context.UnsignedCharTy;
4126 else
4127 Type = Context.CharTy;
4128 break;
4129 case 'b': // boolean
4130 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4131 Type = Context.BoolTy;
4132 break;
4133 case 'z': // size_t.
4134 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4135 Type = Context.getSizeType();
4136 break;
4137 case 'F':
4138 Type = Context.getCFConstantStringType();
4139 break;
4140 case 'a':
4141 Type = Context.getBuiltinVaListType();
4142 assert(!Type.isNull() && "builtin va list type not initialized!");
4143 break;
4144 case 'A':
4145 // This is a "reference" to a va_list; however, what exactly
4146 // this means depends on how va_list is defined. There are two
4147 // different kinds of va_list: ones passed by value, and ones
4148 // passed by reference. An example of a by-value va_list is
4149 // x86, where va_list is a char*. An example of by-ref va_list
4150 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4151 // we want this argument to be a char*&; for x86-64, we want
4152 // it to be a __va_list_tag*.
4153 Type = Context.getBuiltinVaListType();
4154 assert(!Type.isNull() && "builtin va list type not initialized!");
4155 if (Type->isArrayType()) {
4156 Type = Context.getArrayDecayedType(Type);
4157 } else {
4158 Type = Context.getLValueReferenceType(Type);
4159 }
4160 break;
4161 case 'V': {
4162 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004163 unsigned NumElements = strtoul(Str, &End, 10);
4164 assert(End != Str && "Missing vector size");
4165
4166 Str = End;
4167
4168 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4169 Type = Context.getVectorType(ElementType, NumElements);
4170 break;
4171 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004172 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004173 Type = Context.getFILEType();
4174 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004175 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004176 return QualType();
4177 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004178 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004179 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004180 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004181 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004182 else
4183 Type = Context.getjmp_bufType();
4184
Mike Stumpfd612db2009-07-28 23:47:15 +00004185 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004186 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004187 return QualType();
4188 }
4189 break;
Mike Stump782fa302009-07-28 02:25:19 +00004190 }
Chris Lattner86df27b2009-06-14 00:45:47 +00004191
4192 if (!AllowTypeModifiers)
4193 return Type;
4194
4195 Done = false;
4196 while (!Done) {
4197 switch (*Str++) {
4198 default: Done = true; --Str; break;
4199 case '*':
4200 Type = Context.getPointerType(Type);
4201 break;
4202 case '&':
4203 Type = Context.getLValueReferenceType(Type);
4204 break;
4205 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4206 case 'C':
4207 Type = Type.getQualifiedType(QualType::Const);
4208 break;
4209 }
4210 }
4211
4212 return Type;
4213}
4214
4215/// GetBuiltinType - Return the type for the specified builtin.
4216QualType ASTContext::GetBuiltinType(unsigned id,
4217 GetBuiltinTypeError &Error) {
4218 const char *TypeStr = BuiltinInfo.GetTypeString(id);
4219
4220 llvm::SmallVector<QualType, 8> ArgTypes;
4221
4222 Error = GE_None;
4223 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4224 if (Error != GE_None)
4225 return QualType();
4226 while (TypeStr[0] && TypeStr[0] != '.') {
4227 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4228 if (Error != GE_None)
4229 return QualType();
4230
4231 // Do array -> pointer decay. The builtin should use the decayed type.
4232 if (Ty->isArrayType())
4233 Ty = getArrayDecayedType(Ty);
4234
4235 ArgTypes.push_back(Ty);
4236 }
4237
4238 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4239 "'.' should only occur at end of builtin type list!");
4240
4241 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4242 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4243 return getFunctionNoProtoType(ResType);
4244 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4245 TypeStr[0] == '.', 0);
4246}
Eli Friedmana95d7572009-08-19 07:44:53 +00004247
4248QualType
4249ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4250 // Perform the usual unary conversions. We do this early so that
4251 // integral promotions to "int" can allow us to exit early, in the
4252 // lhs == rhs check. Also, for conversion purposes, we ignore any
4253 // qualifiers. For example, "const float" and "float" are
4254 // equivalent.
4255 if (lhs->isPromotableIntegerType())
4256 lhs = getPromotedIntegerType(lhs);
4257 else
4258 lhs = lhs.getUnqualifiedType();
4259 if (rhs->isPromotableIntegerType())
4260 rhs = getPromotedIntegerType(rhs);
4261 else
4262 rhs = rhs.getUnqualifiedType();
4263
4264 // If both types are identical, no conversion is needed.
4265 if (lhs == rhs)
4266 return lhs;
4267
4268 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4269 // The caller can deal with this (e.g. pointer + int).
4270 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4271 return lhs;
4272
4273 // At this point, we have two different arithmetic types.
4274
4275 // Handle complex types first (C99 6.3.1.8p1).
4276 if (lhs->isComplexType() || rhs->isComplexType()) {
4277 // if we have an integer operand, the result is the complex type.
4278 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4279 // convert the rhs to the lhs complex type.
4280 return lhs;
4281 }
4282 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4283 // convert the lhs to the rhs complex type.
4284 return rhs;
4285 }
4286 // This handles complex/complex, complex/float, or float/complex.
4287 // When both operands are complex, the shorter operand is converted to the
4288 // type of the longer, and that is the type of the result. This corresponds
4289 // to what is done when combining two real floating-point operands.
4290 // The fun begins when size promotion occur across type domains.
4291 // From H&S 6.3.4: When one operand is complex and the other is a real
4292 // floating-point type, the less precise type is converted, within it's
4293 // real or complex domain, to the precision of the other type. For example,
4294 // when combining a "long double" with a "double _Complex", the
4295 // "double _Complex" is promoted to "long double _Complex".
4296 int result = getFloatingTypeOrder(lhs, rhs);
4297
4298 if (result > 0) { // The left side is bigger, convert rhs.
4299 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4300 } else if (result < 0) { // The right side is bigger, convert lhs.
4301 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4302 }
4303 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4304 // domains match. This is a requirement for our implementation, C99
4305 // does not require this promotion.
4306 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4307 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4308 return rhs;
4309 } else { // handle "_Complex double, double".
4310 return lhs;
4311 }
4312 }
4313 return lhs; // The domain/size match exactly.
4314 }
4315 // Now handle "real" floating types (i.e. float, double, long double).
4316 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4317 // if we have an integer operand, the result is the real floating type.
4318 if (rhs->isIntegerType()) {
4319 // convert rhs to the lhs floating point type.
4320 return lhs;
4321 }
4322 if (rhs->isComplexIntegerType()) {
4323 // convert rhs to the complex floating point type.
4324 return getComplexType(lhs);
4325 }
4326 if (lhs->isIntegerType()) {
4327 // convert lhs to the rhs floating point type.
4328 return rhs;
4329 }
4330 if (lhs->isComplexIntegerType()) {
4331 // convert lhs to the complex floating point type.
4332 return getComplexType(rhs);
4333 }
4334 // We have two real floating types, float/complex combos were handled above.
4335 // Convert the smaller operand to the bigger result.
4336 int result = getFloatingTypeOrder(lhs, rhs);
4337 if (result > 0) // convert the rhs
4338 return lhs;
4339 assert(result < 0 && "illegal float comparison");
4340 return rhs; // convert the lhs
4341 }
4342 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4343 // Handle GCC complex int extension.
4344 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4345 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4346
4347 if (lhsComplexInt && rhsComplexInt) {
4348 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4349 rhsComplexInt->getElementType()) >= 0)
4350 return lhs; // convert the rhs
4351 return rhs;
4352 } else if (lhsComplexInt && rhs->isIntegerType()) {
4353 // convert the rhs to the lhs complex type.
4354 return lhs;
4355 } else if (rhsComplexInt && lhs->isIntegerType()) {
4356 // convert the lhs to the rhs complex type.
4357 return rhs;
4358 }
4359 }
4360 // Finally, we have two differing integer types.
4361 // The rules for this case are in C99 6.3.1.8
4362 int compare = getIntegerTypeOrder(lhs, rhs);
4363 bool lhsSigned = lhs->isSignedIntegerType(),
4364 rhsSigned = rhs->isSignedIntegerType();
4365 QualType destType;
4366 if (lhsSigned == rhsSigned) {
4367 // Same signedness; use the higher-ranked type
4368 destType = compare >= 0 ? lhs : rhs;
4369 } else if (compare != (lhsSigned ? 1 : -1)) {
4370 // The unsigned type has greater than or equal rank to the
4371 // signed type, so use the unsigned type
4372 destType = lhsSigned ? rhs : lhs;
4373 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4374 // The two types are different widths; if we are here, that
4375 // means the signed type is larger than the unsigned type, so
4376 // use the signed type.
4377 destType = lhsSigned ? lhs : rhs;
4378 } else {
4379 // The signed type is higher-ranked than the unsigned type,
4380 // but isn't actually any bigger (like unsigned int and long
4381 // on most 32-bit systems). Use the unsigned type corresponding
4382 // to the signed type.
4383 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4384 }
4385 return destType;
4386}