blob: 51815d5f319a63e32448ee9b5b8bd906ab45118b [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"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000027#include "RecordLayoutBuilder.h"
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
31enum FloatingRank {
32 FloatRank, DoubleRank, LongDoubleRank
33};
34
Chris Lattner61710852008-10-05 17:34:18 +000035ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
36 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000037 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000038 Builtin::Context &builtins,
39 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000040 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000041 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
42 sigjmp_bufDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000043 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
44 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000045 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000046 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000047 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000048 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000049}
50
Reid Spencer5f016e22007-07-11 17:01:13 +000051ASTContext::~ASTContext() {
52 // Deallocate all the types.
53 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000054 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000055 Types.pop_back();
56 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000057
Nuno Lopesb74668e2008-12-17 22:30:25 +000058 {
59 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
60 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
61 while (I != E) {
62 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
63 delete R;
64 }
65 }
66
67 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000068 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
69 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 while (I != E) {
71 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
72 delete R;
73 }
74 }
75
Douglas Gregorab452ba2009-03-26 23:50:42 +000076 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000077 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
78 NNS = NestedNameSpecifiers.begin(),
79 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000080 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000081 /* Increment in loop */)
82 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000083
84 if (GlobalNestedNameSpecifier)
85 GlobalNestedNameSpecifier->Destroy(*this);
86
Eli Friedmanb26153c2008-05-27 03:08:09 +000087 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000088}
89
Douglas Gregor2cf26342009-04-09 22:27:44 +000090void
91ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
92 ExternalSource.reset(Source.take());
93}
94
Reid Spencer5f016e22007-07-11 17:01:13 +000095void ASTContext::PrintStats() const {
96 fprintf(stderr, "*** AST Context Stats:\n");
97 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000098
Douglas Gregordbe833d2009-05-26 14:40:08 +000099 unsigned counts[] = {
100#define TYPE(Name, Parent) 0,
101#define ABSTRACT_TYPE(Name, Parent)
102#include "clang/AST/TypeNodes.def"
103 0 // Extra
104 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
107 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000108 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 }
110
Douglas Gregordbe833d2009-05-26 14:40:08 +0000111 unsigned Idx = 0;
112 unsigned TotalBytes = 0;
113#define TYPE(Name, Parent) \
114 if (counts[Idx]) \
115 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
116 TotalBytes += counts[Idx] * sizeof(Name##Type); \
117 ++Idx;
118#define ABSTRACT_TYPE(Name, Parent)
119#include "clang/AST/TypeNodes.def"
120
121 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000122
123 if (ExternalSource.get()) {
124 fprintf(stderr, "\n");
125 ExternalSource->PrintStats();
126 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000127}
128
129
130void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000131 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000132}
133
Reid Spencer5f016e22007-07-11 17:01:13 +0000134void ASTContext::InitBuiltinTypes() {
135 assert(VoidTy.isNull() && "Context reinitialized?");
136
137 // C99 6.2.5p19.
138 InitBuiltinType(VoidTy, BuiltinType::Void);
139
140 // C99 6.2.5p2.
141 InitBuiltinType(BoolTy, BuiltinType::Bool);
142 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000143 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 InitBuiltinType(CharTy, BuiltinType::Char_S);
145 else
146 InitBuiltinType(CharTy, BuiltinType::Char_U);
147 // C99 6.2.5p4.
148 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
149 InitBuiltinType(ShortTy, BuiltinType::Short);
150 InitBuiltinType(IntTy, BuiltinType::Int);
151 InitBuiltinType(LongTy, BuiltinType::Long);
152 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
153
154 // C99 6.2.5p6.
155 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
156 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
157 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
158 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
159 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
160
161 // C99 6.2.5p10.
162 InitBuiltinType(FloatTy, BuiltinType::Float);
163 InitBuiltinType(DoubleTy, BuiltinType::Double);
164 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000165
Chris Lattner2df9ced2009-04-30 02:43:43 +0000166 // GNU extension, 128-bit integers.
167 InitBuiltinType(Int128Ty, BuiltinType::Int128);
168 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
169
Chris Lattner3a250322009-02-26 23:43:47 +0000170 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
171 InitBuiltinType(WCharTy, BuiltinType::WChar);
172 else // C99
173 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000174
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000175 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
176 InitBuiltinType(Char16Ty, BuiltinType::Char16);
177 else // C99
178 Char16Ty = getFromTargetType(Target.getChar16Type());
179
180 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
181 InitBuiltinType(Char32Ty, BuiltinType::Char32);
182 else // C99
183 Char32Ty = getFromTargetType(Target.getChar32Type());
184
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000186 InitBuiltinType(OverloadTy, BuiltinType::Overload);
187
188 // Placeholder type for type-dependent expressions whose type is
189 // completely unknown. No code should ever check a type against
190 // DependentTy and users should never see it; however, it is here to
191 // help diagnose failures to properly check for type-dependent
192 // expressions.
193 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194
Anders Carlssone89d1592009-06-26 18:41:36 +0000195 // Placeholder type for C++0x auto declarations whose real type has
196 // not yet been deduced.
197 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
198
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // C99 6.2.5p11.
200 FloatComplexTy = getComplexType(FloatTy);
201 DoubleComplexTy = getComplexType(DoubleTy);
202 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203
Steve Naroff7e219e42007-10-15 14:41:52 +0000204 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000205
Steve Naroffde2e22d2009-07-15 18:40:39 +0000206 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
207 ObjCIdTypedefType = QualType();
208 ObjCClassTypedefType = QualType();
209
210 // Builtin types for 'id' and 'Class'.
211 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
212 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000213
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000214 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000215
216 // void * type
217 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000218
219 // nullptr type (C++0x 2.14.7)
220 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000221}
222
Douglas Gregor7caa6822009-07-24 20:34:43 +0000223VarDecl *ASTContext::getInstantiatedFromStaticDataMember(VarDecl *Var) {
224 assert(Var->isStaticDataMember() && "Not a static data member");
225 llvm::DenseMap<VarDecl *, VarDecl *>::iterator Pos
226 = InstantiatedFromStaticDataMember.find(Var);
227 if (Pos == InstantiatedFromStaticDataMember.end())
228 return 0;
229
230 return Pos->second;
231}
232
233void
234ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) {
235 assert(Inst->isStaticDataMember() && "Not a static data member");
236 assert(Tmpl->isStaticDataMember() && "Not a static data member");
237 assert(!InstantiatedFromStaticDataMember[Inst] &&
238 "Already noted what static data member was instantiated from");
239 InstantiatedFromStaticDataMember[Inst] = Tmpl;
240}
241
Douglas Gregor2e222532009-07-02 17:08:52 +0000242namespace {
243 class BeforeInTranslationUnit
244 : std::binary_function<SourceRange, SourceRange, bool> {
245 SourceManager *SourceMgr;
246
247 public:
248 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
249
250 bool operator()(SourceRange X, SourceRange Y) {
251 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
252 }
253 };
254}
255
256/// \brief Determine whether the given comment is a Doxygen-style comment.
257///
258/// \param Start the start of the comment text.
259///
260/// \param End the end of the comment text.
261///
262/// \param Member whether we want to check whether this is a member comment
263/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
264/// we only return true when we find a non-member comment.
265static bool
266isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
267 bool Member = false) {
268 const char *BufferStart
269 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
270 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
271 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
272
273 if (End - Start < 4)
274 return false;
275
276 assert(Start[0] == '/' && "Not a comment?");
277 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
278 return false;
279 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
280 return false;
281
282 return (Start[3] == '<') == Member;
283}
284
285/// \brief Retrieve the comment associated with the given declaration, if
286/// it has one.
287const char *ASTContext::getCommentForDecl(const Decl *D) {
288 if (!D)
289 return 0;
290
291 // Check whether we have cached a comment string for this declaration
292 // already.
293 llvm::DenseMap<const Decl *, std::string>::iterator Pos
294 = DeclComments.find(D);
295 if (Pos != DeclComments.end())
296 return Pos->second.c_str();
297
298 // If we have an external AST source and have not yet loaded comments from
299 // that source, do so now.
300 if (ExternalSource && !LoadedExternalComments) {
301 std::vector<SourceRange> LoadedComments;
302 ExternalSource->ReadComments(LoadedComments);
303
304 if (!LoadedComments.empty())
305 Comments.insert(Comments.begin(), LoadedComments.begin(),
306 LoadedComments.end());
307
308 LoadedExternalComments = true;
309 }
310
311 // If there are no comments anywhere, we won't find anything.
312 if (Comments.empty())
313 return 0;
314
315 // If the declaration doesn't map directly to a location in a file, we
316 // can't find the comment.
317 SourceLocation DeclStartLoc = D->getLocStart();
318 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
319 return 0;
320
321 // Find the comment that occurs just before this declaration.
322 std::vector<SourceRange>::iterator LastComment
323 = std::lower_bound(Comments.begin(), Comments.end(),
324 SourceRange(DeclStartLoc),
325 BeforeInTranslationUnit(&SourceMgr));
326
327 // Decompose the location for the start of the declaration and find the
328 // beginning of the file buffer.
329 std::pair<FileID, unsigned> DeclStartDecomp
330 = SourceMgr.getDecomposedLoc(DeclStartLoc);
331 const char *FileBufferStart
332 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
333
334 // First check whether we have a comment for a member.
335 if (LastComment != Comments.end() &&
336 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
337 isDoxygenComment(SourceMgr, *LastComment, true)) {
338 std::pair<FileID, unsigned> LastCommentEndDecomp
339 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
340 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
341 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
342 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
343 LastCommentEndDecomp.second)) {
344 // The Doxygen member comment comes after the declaration starts and
345 // is on the same line and in the same file as the declaration. This
346 // is the comment we want.
347 std::string &Result = DeclComments[D];
348 Result.append(FileBufferStart +
349 SourceMgr.getFileOffset(LastComment->getBegin()),
350 FileBufferStart + LastCommentEndDecomp.second + 1);
351 return Result.c_str();
352 }
353 }
354
355 if (LastComment == Comments.begin())
356 return 0;
357 --LastComment;
358
359 // Decompose the end of the comment.
360 std::pair<FileID, unsigned> LastCommentEndDecomp
361 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
362
363 // If the comment and the declaration aren't in the same file, then they
364 // aren't related.
365 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
366 return 0;
367
368 // Check that we actually have a Doxygen comment.
369 if (!isDoxygenComment(SourceMgr, *LastComment))
370 return 0;
371
372 // Compute the starting line for the declaration and for the end of the
373 // comment (this is expensive).
374 unsigned DeclStartLine
375 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
376 unsigned CommentEndLine
377 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
378 LastCommentEndDecomp.second);
379
380 // If the comment does not end on the line prior to the declaration, then
381 // the comment is not associated with the declaration at all.
382 if (CommentEndLine + 1 != DeclStartLine)
383 return 0;
384
385 // We have a comment, but there may be more comments on the previous lines.
386 // Keep looking so long as the comments are still Doxygen comments and are
387 // still adjacent.
388 unsigned ExpectedLine
389 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
390 std::vector<SourceRange>::iterator FirstComment = LastComment;
391 while (FirstComment != Comments.begin()) {
392 // Look at the previous comment
393 --FirstComment;
394 std::pair<FileID, unsigned> Decomp
395 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
396
397 // If this previous comment is in a different file, we're done.
398 if (Decomp.first != DeclStartDecomp.first) {
399 ++FirstComment;
400 break;
401 }
402
403 // If this comment is not a Doxygen comment, we're done.
404 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
405 ++FirstComment;
406 break;
407 }
408
409 // If the line number is not what we expected, we're done.
410 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
411 if (Line != ExpectedLine) {
412 ++FirstComment;
413 break;
414 }
415
416 // Set the next expected line number.
417 ExpectedLine
418 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
419 }
420
421 // The iterator range [FirstComment, LastComment] contains all of the
422 // BCPL comments that, together, are associated with this declaration.
423 // Form a single comment block string for this declaration that concatenates
424 // all of these comments.
425 std::string &Result = DeclComments[D];
426 while (FirstComment != LastComment) {
427 std::pair<FileID, unsigned> DecompStart
428 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
429 std::pair<FileID, unsigned> DecompEnd
430 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
431 Result.append(FileBufferStart + DecompStart.second,
432 FileBufferStart + DecompEnd.second + 1);
433 ++FirstComment;
434 }
435
436 // Append the last comment line.
437 Result.append(FileBufferStart +
438 SourceMgr.getFileOffset(LastComment->getBegin()),
439 FileBufferStart + LastCommentEndDecomp.second + 1);
440 return Result.c_str();
441}
442
Chris Lattner464175b2007-07-18 17:52:12 +0000443//===----------------------------------------------------------------------===//
444// Type Sizing and Analysis
445//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000446
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000447/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
448/// scalar floating point type.
449const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
450 const BuiltinType *BT = T->getAsBuiltinType();
451 assert(BT && "Not a floating point type!");
452 switch (BT->getKind()) {
453 default: assert(0 && "Not a floating point type!");
454 case BuiltinType::Float: return Target.getFloatFormat();
455 case BuiltinType::Double: return Target.getDoubleFormat();
456 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
457 }
458}
459
Chris Lattneraf707ab2009-01-24 21:53:27 +0000460/// getDeclAlign - Return a conservative estimate of the alignment of the
461/// specified decl. Note that bitfields do not have a valid alignment, so
462/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000463unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000464 unsigned Align = Target.getCharWidth();
465
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000466 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000467 Align = std::max(Align, AA->getAlignment());
468
Chris Lattneraf707ab2009-01-24 21:53:27 +0000469 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
470 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000471 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000472 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000473 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000474 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
475 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000476 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
477 T = cast<ArrayType>(T)->getElementType();
478
479 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
480 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000481 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000482
483 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000484}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000485
Chris Lattnera7674d82007-07-13 22:13:22 +0000486/// getTypeSize - Return the size of the specified type, in bits. This method
487/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000488std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000489ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000490 uint64_t Width=0;
491 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000492 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000493#define TYPE(Class, Base)
494#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000495#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000496#define DEPENDENT_TYPE(Class, Base) case Type::Class:
497#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000498 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000499 break;
500
Chris Lattner692233e2007-07-13 22:27:08 +0000501 case Type::FunctionNoProto:
502 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000503 // GCC extension: alignof(function) = 32 bits
504 Width = 0;
505 Align = 32;
506 break;
507
Douglas Gregor72564e72009-02-26 23:50:07 +0000508 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000509 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000510 Width = 0;
511 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
512 break;
513
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000514 case Type::ConstantArrayWithExpr:
515 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000516 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000517 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000518
Chris Lattner98be4942008-03-05 18:54:05 +0000519 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000520 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000521 Align = EltInfo.second;
522 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000523 }
Nate Begeman213541a2008-04-18 23:10:10 +0000524 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000525 case Type::Vector: {
526 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000527 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000528 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000529 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000530 // If the alignment is not a power of 2, round up to the next power of 2.
531 // This happens for non-power-of-2 length vectors.
532 // FIXME: this should probably be a target property.
533 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000534 break;
535 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000536
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000537 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000538 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000539 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000540 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000541 // GCC extension: alignof(void) = 8 bits.
542 Width = 0;
543 Align = 8;
544 break;
545
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000546 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000547 Width = Target.getBoolWidth();
548 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000549 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000550 case BuiltinType::Char_S:
551 case BuiltinType::Char_U:
552 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000553 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000554 Width = Target.getCharWidth();
555 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000556 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000557 case BuiltinType::WChar:
558 Width = Target.getWCharWidth();
559 Align = Target.getWCharAlign();
560 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000561 case BuiltinType::Char16:
562 Width = Target.getChar16Width();
563 Align = Target.getChar16Align();
564 break;
565 case BuiltinType::Char32:
566 Width = Target.getChar32Width();
567 Align = Target.getChar32Align();
568 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000569 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000570 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000571 Width = Target.getShortWidth();
572 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000573 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000574 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000575 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000576 Width = Target.getIntWidth();
577 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000578 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000579 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000580 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000581 Width = Target.getLongWidth();
582 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000583 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000584 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000585 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000586 Width = Target.getLongLongWidth();
587 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000588 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000589 case BuiltinType::Int128:
590 case BuiltinType::UInt128:
591 Width = 128;
592 Align = 128; // int128_t is 128-bit aligned on all targets.
593 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000594 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000595 Width = Target.getFloatWidth();
596 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000597 break;
598 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000599 Width = Target.getDoubleWidth();
600 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000601 break;
602 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000603 Width = Target.getLongDoubleWidth();
604 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000605 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000606 case BuiltinType::NullPtr:
607 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
608 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000609 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000610 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000611 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000612 case Type::FixedWidthInt:
613 // FIXME: This isn't precisely correct; the width/alignment should depend
614 // on the available types for the target
615 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000616 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000617 Align = Width;
618 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000619 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000620 // FIXME: Pointers into different addr spaces could have different sizes and
621 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000622 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000623 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000624 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000625 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000626 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000627 case Type::BlockPointer: {
628 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
629 Width = Target.getPointerWidth(AS);
630 Align = Target.getPointerAlign(AS);
631 break;
632 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000633 case Type::Pointer: {
634 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000635 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000636 Align = Target.getPointerAlign(AS);
637 break;
638 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000639 case Type::LValueReference:
640 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000641 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000642 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000643 // FIXME: This is wrong for struct layout: a reference in a struct has
644 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000645 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000646 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000647 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
648 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
649 // If we ever want to support other ABIs this needs to be abstracted.
650
Sebastian Redlf30208a2009-01-24 21:16:55 +0000651 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000652 std::pair<uint64_t, unsigned> PtrDiffInfo =
653 getTypeInfo(getPointerDiffType());
654 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000655 if (Pointee->isFunctionType())
656 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000657 Align = PtrDiffInfo.second;
658 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000659 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000660 case Type::Complex: {
661 // Complex types have the same alignment as their elements, but twice the
662 // size.
663 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000664 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000665 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000666 Align = EltInfo.second;
667 break;
668 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000669 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000670 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000671 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
672 Width = Layout.getSize();
673 Align = Layout.getAlignment();
674 break;
675 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000676 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000677 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000678 const TagType *TT = cast<TagType>(T);
679
680 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000681 Width = 1;
682 Align = 1;
683 break;
684 }
685
Daniel Dunbar1d751182008-11-08 05:48:37 +0000686 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000687 return getTypeInfo(ET->getDecl()->getIntegerType());
688
Daniel Dunbar1d751182008-11-08 05:48:37 +0000689 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000690 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
691 Width = Layout.getSize();
692 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000693 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000694 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000695
Douglas Gregor18857642009-04-30 17:32:17 +0000696 case Type::Typedef: {
697 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000698 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000699 Align = Aligned->getAlignment();
700 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
701 } else
702 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000703 break;
Chris Lattner71763312008-04-06 22:05:18 +0000704 }
Douglas Gregor18857642009-04-30 17:32:17 +0000705
706 case Type::TypeOfExpr:
707 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
708 .getTypePtr());
709
710 case Type::TypeOf:
711 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
712
Anders Carlsson395b4752009-06-24 19:06:50 +0000713 case Type::Decltype:
714 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
715 .getTypePtr());
716
Douglas Gregor18857642009-04-30 17:32:17 +0000717 case Type::QualifiedName:
718 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
719
720 case Type::TemplateSpecialization:
721 assert(getCanonicalType(T) != T &&
722 "Cannot request the size of a dependent type");
723 // FIXME: this is likely to be wrong once we support template
724 // aliases, since a template alias could refer to a typedef that
725 // has an __aligned__ attribute on it.
726 return getTypeInfo(getCanonicalType(T));
727 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000728
Chris Lattner464175b2007-07-18 17:52:12 +0000729 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000730 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000731}
732
Chris Lattner34ebde42009-01-27 18:08:34 +0000733/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
734/// type for the current target in bits. This can be different than the ABI
735/// alignment in cases where it is beneficial for performance to overalign
736/// a data type.
737unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
738 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000739
740 // Double and long long should be naturally aligned if possible.
741 if (const ComplexType* CT = T->getAsComplexType())
742 T = CT->getElementType().getTypePtr();
743 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
744 T->isSpecificBuiltinType(BuiltinType::LongLong))
745 return std::max(ABIAlign, (unsigned)getTypeSize(T));
746
Chris Lattner34ebde42009-01-27 18:08:34 +0000747 return ABIAlign;
748}
749
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000750static void CollectLocalObjCIvars(ASTContext *Ctx,
751 const ObjCInterfaceDecl *OI,
752 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000753 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
754 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000755 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000756 if (!IVDecl->isInvalidDecl())
757 Fields.push_back(cast<FieldDecl>(IVDecl));
758 }
759}
760
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000761void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
762 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
763 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
764 CollectObjCIvars(SuperClass, Fields);
765 CollectLocalObjCIvars(this, OI, Fields);
766}
767
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000768/// ShallowCollectObjCIvars -
769/// Collect all ivars, including those synthesized, in the current class.
770///
771void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
772 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
773 bool CollectSynthesized) {
774 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
775 E = OI->ivar_end(); I != E; ++I) {
776 Ivars.push_back(*I);
777 }
778 if (CollectSynthesized)
779 CollectSynthesizedIvars(OI, Ivars);
780}
781
Fariborz Jahanian98200742009-05-12 18:14:29 +0000782void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
783 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000784 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
785 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000786 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
787 Ivars.push_back(Ivar);
788
789 // Also look into nested protocols.
790 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
791 E = PD->protocol_end(); P != E; ++P)
792 CollectProtocolSynthesizedIvars(*P, Ivars);
793}
794
795/// CollectSynthesizedIvars -
796/// This routine collect synthesized ivars for the designated class.
797///
798void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
799 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000800 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
801 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000802 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
803 Ivars.push_back(Ivar);
804 }
805 // Also look into interface's protocol list for properties declared
806 // in the protocol and whose ivars are synthesized.
807 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
808 PE = OI->protocol_end(); P != PE; ++P) {
809 ObjCProtocolDecl *PD = (*P);
810 CollectProtocolSynthesizedIvars(PD, Ivars);
811 }
812}
813
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000814unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
815 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000816 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
817 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000818 if ((*I)->getPropertyIvarDecl())
819 ++count;
820
821 // Also look into nested protocols.
822 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
823 E = PD->protocol_end(); P != E; ++P)
824 count += CountProtocolSynthesizedIvars(*P);
825 return count;
826}
827
828unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
829{
830 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000831 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
832 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000833 if ((*I)->getPropertyIvarDecl())
834 ++count;
835 }
836 // Also look into interface's protocol list for properties declared
837 // in the protocol and whose ivars are synthesized.
838 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
839 PE = OI->protocol_end(); P != PE; ++P) {
840 ObjCProtocolDecl *PD = (*P);
841 count += CountProtocolSynthesizedIvars(PD);
842 }
843 return count;
844}
845
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000846/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
847ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
848 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
849 I = ObjCImpls.find(D);
850 if (I != ObjCImpls.end())
851 return cast<ObjCImplementationDecl>(I->second);
852 return 0;
853}
854/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
855ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
856 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
857 I = ObjCImpls.find(D);
858 if (I != ObjCImpls.end())
859 return cast<ObjCCategoryImplDecl>(I->second);
860 return 0;
861}
862
863/// \brief Set the implementation of ObjCInterfaceDecl.
864void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
865 ObjCImplementationDecl *ImplD) {
866 assert(IFaceD && ImplD && "Passed null params");
867 ObjCImpls[IFaceD] = ImplD;
868}
869/// \brief Set the implementation of ObjCCategoryDecl.
870void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
871 ObjCCategoryImplDecl *ImplD) {
872 assert(CatD && ImplD && "Passed null params");
873 ObjCImpls[CatD] = ImplD;
874}
875
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000876/// getInterfaceLayoutImpl - Get or compute information about the
877/// layout of the given interface.
878///
879/// \param Impl - If given, also include the layout of the interface's
880/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000881const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000882ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
883 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000884 assert(!D->isForwardDecl() && "Invalid interface decl!");
885
Devang Patel44a3dde2008-06-04 21:54:36 +0000886 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000887 ObjCContainerDecl *Key =
888 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
889 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
890 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000891
Daniel Dunbar453addb2009-05-03 11:16:44 +0000892 // Add in synthesized ivar count if laying out an implementation.
893 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000894 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000895 unsigned SynthCount = CountSynthesizedIvars(D);
896 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000897 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000898 // entry. Note we can't cache this because we simply free all
899 // entries later; however we shouldn't look up implementations
900 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000901 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000902 return getObjCLayout(D, 0);
903 }
904
Anders Carlsson29445a02009-07-18 21:19:52 +0000905 const ASTRecordLayout *NewEntry =
906 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
907 ObjCLayouts[Key] = NewEntry;
908
Devang Patel44a3dde2008-06-04 21:54:36 +0000909 return *NewEntry;
910}
911
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000912const ASTRecordLayout &
913ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
914 return getObjCLayout(D, 0);
915}
916
917const ASTRecordLayout &
918ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
919 return getObjCLayout(D->getClassInterface(), D);
920}
921
Devang Patel88a981b2007-11-01 19:11:01 +0000922/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000923/// specified record (struct/union/class), which indicates its size and field
924/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000925const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000926 D = D->getDefinition(*this);
927 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000928
Chris Lattner464175b2007-07-18 17:52:12 +0000929 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +0000930 // Note that we can't save a reference to the entry because this function
931 // is recursive.
932 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000933 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000934
Anders Carlsson29445a02009-07-18 21:19:52 +0000935 const ASTRecordLayout *NewEntry =
936 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000937 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000938
Chris Lattner5d2a6302007-07-18 18:26:58 +0000939 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000940}
941
Chris Lattnera7674d82007-07-13 22:13:22 +0000942//===----------------------------------------------------------------------===//
943// Type creation/memoization methods
944//===----------------------------------------------------------------------===//
945
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000946QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000947 QualType CanT = getCanonicalType(T);
948 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000949 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000950
951 // If we are composing extended qualifiers together, merge together into one
952 // ExtQualType node.
953 unsigned CVRQuals = T.getCVRQualifiers();
954 QualType::GCAttrTypes GCAttr = QualType::GCNone;
955 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000956
Chris Lattnerb7d25532009-02-18 22:53:11 +0000957 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
958 // If this type already has an address space specified, it cannot get
959 // another one.
960 assert(EQT->getAddressSpace() == 0 &&
961 "Type cannot be in multiple addr spaces!");
962 GCAttr = EQT->getObjCGCAttr();
963 TypeNode = EQT->getBaseType();
964 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000965
Chris Lattnerb7d25532009-02-18 22:53:11 +0000966 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000967 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +0000968 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000969 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000970 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000971 return QualType(EXTQy, CVRQuals);
972
Christopher Lambebb97e92008-02-04 02:31:56 +0000973 // If the base type isn't canonical, this won't be a canonical type either,
974 // so fill in the canonical type field.
975 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000976 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000977 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000978
Chris Lattnerb7d25532009-02-18 22:53:11 +0000979 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000980 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000981 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000982 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000983 ExtQualType *New =
984 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000985 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000986 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000987 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000988}
989
Chris Lattnerb7d25532009-02-18 22:53:11 +0000990QualType ASTContext::getObjCGCQualType(QualType T,
991 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000992 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000993 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000994 return T;
995
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000996 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000997 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000998 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000999 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1000 return getPointerType(ResultType);
1001 }
1002 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001003 // If we are composing extended qualifiers together, merge together into one
1004 // ExtQualType node.
1005 unsigned CVRQuals = T.getCVRQualifiers();
1006 Type *TypeNode = T.getTypePtr();
1007 unsigned AddressSpace = 0;
1008
1009 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
Mike Stump24556362009-07-25 21:26:53 +00001010 // If this type already has an ObjCGC specified, it cannot get
Chris Lattnerb7d25532009-02-18 22:53:11 +00001011 // another one.
1012 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
Mike Stump24556362009-07-25 21:26:53 +00001013 "Type cannot have multiple ObjCGCs!");
Chris Lattnerb7d25532009-02-18 22:53:11 +00001014 AddressSpace = EQT->getAddressSpace();
1015 TypeNode = EQT->getBaseType();
1016 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001017
1018 // Check if we've already instantiated an gc qual'd type of this type.
1019 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001020 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001021 void *InsertPos = 0;
1022 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001023 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001024
1025 // If the base type isn't canonical, this won't be a canonical type either,
1026 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001027 // FIXME: Isn't this also not canonical if the base type is a array
1028 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001029 QualType Canonical;
1030 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001031 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001032
Chris Lattnerb7d25532009-02-18 22:53:11 +00001033 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001034 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1035 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1036 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001037 ExtQualType *New =
1038 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001039 ExtQualTypes.InsertNode(New, InsertPos);
1040 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001041 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001042}
Chris Lattnera7674d82007-07-13 22:13:22 +00001043
Mike Stump24556362009-07-25 21:26:53 +00001044QualType ASTContext::getNoReturnType(QualType T) {
Mike Stump6dcbc292009-07-25 23:24:03 +00001045 QualifierSet qs;
1046 qs.strip(T);
Mike Stump24556362009-07-25 21:26:53 +00001047 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001048 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001049 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001050 ResultType = getPointerType(ResultType);
1051 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1052 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001053 }
1054 if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001055 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001056 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001057 ResultType = getBlockPointerType(ResultType);
1058 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1059 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001060 }
1061 if (!T->isFunctionType())
1062 assert(0 && "can't noreturn qualify non-pointer to function or block type");
1063
Mike Stumpe24aea22009-07-27 22:25:19 +00001064 if (const FunctionNoProtoType *F = T->getAsFunctionNoProtoType()) {
Mike Stump24556362009-07-25 21:26:53 +00001065 return getFunctionNoProtoType(F->getResultType(), true);
1066 }
Mike Stumpe24aea22009-07-27 22:25:19 +00001067 const FunctionProtoType *F = T->getAsFunctionProtoType();
Mike Stump24556362009-07-25 21:26:53 +00001068 return getFunctionType(F->getResultType(), F->arg_type_begin(),
1069 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1070 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1071 F->getNumExceptions(), F->exception_begin(), true);
1072}
1073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074/// getComplexType - Return the uniqued reference to the type for a complex
1075/// number with the specified element type.
1076QualType ASTContext::getComplexType(QualType T) {
1077 // Unique pointers, to guarantee there is only one pointer of a particular
1078 // structure.
1079 llvm::FoldingSetNodeID ID;
1080 ComplexType::Profile(ID, T);
1081
1082 void *InsertPos = 0;
1083 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1084 return QualType(CT, 0);
1085
1086 // If the pointee type isn't canonical, this won't be a canonical type either,
1087 // so fill in the canonical type field.
1088 QualType Canonical;
1089 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001090 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001091
1092 // Get the new insert position for the node we care about.
1093 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001094 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 }
Steve Narofff83820b2009-01-27 22:08:43 +00001096 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 Types.push_back(New);
1098 ComplexTypes.InsertNode(New, InsertPos);
1099 return QualType(New, 0);
1100}
1101
Eli Friedmanf98aba32009-02-13 02:31:07 +00001102QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1103 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1104 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1105 FixedWidthIntType *&Entry = Map[Width];
1106 if (!Entry)
1107 Entry = new FixedWidthIntType(Width, Signed);
1108 return QualType(Entry, 0);
1109}
Reid Spencer5f016e22007-07-11 17:01:13 +00001110
1111/// getPointerType - Return the uniqued reference to the type for a pointer to
1112/// the specified type.
1113QualType ASTContext::getPointerType(QualType T) {
1114 // Unique pointers, to guarantee there is only one pointer of a particular
1115 // structure.
1116 llvm::FoldingSetNodeID ID;
1117 PointerType::Profile(ID, T);
1118
1119 void *InsertPos = 0;
1120 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1121 return QualType(PT, 0);
1122
1123 // If the pointee type isn't canonical, this won't be a canonical type either,
1124 // so fill in the canonical type field.
1125 QualType Canonical;
1126 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001127 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001128
1129 // Get the new insert position for the node we care about.
1130 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001131 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 }
Steve Narofff83820b2009-01-27 22:08:43 +00001133 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 Types.push_back(New);
1135 PointerTypes.InsertNode(New, InsertPos);
1136 return QualType(New, 0);
1137}
1138
Steve Naroff5618bd42008-08-27 16:04:49 +00001139/// getBlockPointerType - Return the uniqued reference to the type for
1140/// a pointer to the specified block.
1141QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001142 assert(T->isFunctionType() && "block of function types only");
1143 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001144 // structure.
1145 llvm::FoldingSetNodeID ID;
1146 BlockPointerType::Profile(ID, T);
1147
1148 void *InsertPos = 0;
1149 if (BlockPointerType *PT =
1150 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1151 return QualType(PT, 0);
1152
Steve Naroff296e8d52008-08-28 19:20:44 +00001153 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001154 // type either so fill in the canonical type field.
1155 QualType Canonical;
1156 if (!T->isCanonical()) {
1157 Canonical = getBlockPointerType(getCanonicalType(T));
1158
1159 // Get the new insert position for the node we care about.
1160 BlockPointerType *NewIP =
1161 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001162 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001163 }
Steve Narofff83820b2009-01-27 22:08:43 +00001164 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001165 Types.push_back(New);
1166 BlockPointerTypes.InsertNode(New, InsertPos);
1167 return QualType(New, 0);
1168}
1169
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001170/// getLValueReferenceType - Return the uniqued reference to the type for an
1171/// lvalue reference to the specified type.
1172QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 // Unique pointers, to guarantee there is only one pointer of a particular
1174 // structure.
1175 llvm::FoldingSetNodeID ID;
1176 ReferenceType::Profile(ID, T);
1177
1178 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001179 if (LValueReferenceType *RT =
1180 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // If the referencee type isn't canonical, this won't be a canonical type
1184 // either, so fill in the canonical type field.
1185 QualType Canonical;
1186 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001187 Canonical = getLValueReferenceType(getCanonicalType(T));
1188
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001190 LValueReferenceType *NewIP =
1191 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001192 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 }
1194
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001195 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001197 LValueReferenceTypes.InsertNode(New, InsertPos);
1198 return QualType(New, 0);
1199}
1200
1201/// getRValueReferenceType - Return the uniqued reference to the type for an
1202/// rvalue reference to the specified type.
1203QualType ASTContext::getRValueReferenceType(QualType T) {
1204 // Unique pointers, to guarantee there is only one pointer of a particular
1205 // structure.
1206 llvm::FoldingSetNodeID ID;
1207 ReferenceType::Profile(ID, T);
1208
1209 void *InsertPos = 0;
1210 if (RValueReferenceType *RT =
1211 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1212 return QualType(RT, 0);
1213
1214 // If the referencee type isn't canonical, this won't be a canonical type
1215 // either, so fill in the canonical type field.
1216 QualType Canonical;
1217 if (!T->isCanonical()) {
1218 Canonical = getRValueReferenceType(getCanonicalType(T));
1219
1220 // Get the new insert position for the node we care about.
1221 RValueReferenceType *NewIP =
1222 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1223 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1224 }
1225
1226 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1227 Types.push_back(New);
1228 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 return QualType(New, 0);
1230}
1231
Sebastian Redlf30208a2009-01-24 21:16:55 +00001232/// getMemberPointerType - Return the uniqued reference to the type for a
1233/// member pointer to the specified type, in the specified class.
1234QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1235{
1236 // Unique pointers, to guarantee there is only one pointer of a particular
1237 // structure.
1238 llvm::FoldingSetNodeID ID;
1239 MemberPointerType::Profile(ID, T, Cls);
1240
1241 void *InsertPos = 0;
1242 if (MemberPointerType *PT =
1243 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1244 return QualType(PT, 0);
1245
1246 // If the pointee or class type isn't canonical, this won't be a canonical
1247 // type either, so fill in the canonical type field.
1248 QualType Canonical;
1249 if (!T->isCanonical()) {
1250 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1251
1252 // Get the new insert position for the node we care about.
1253 MemberPointerType *NewIP =
1254 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1255 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1256 }
Steve Narofff83820b2009-01-27 22:08:43 +00001257 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001258 Types.push_back(New);
1259 MemberPointerTypes.InsertNode(New, InsertPos);
1260 return QualType(New, 0);
1261}
1262
Steve Narofffb22d962007-08-30 01:06:46 +00001263/// getConstantArrayType - Return the unique reference to the type for an
1264/// array of the specified element type.
1265QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001266 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001267 ArrayType::ArraySizeModifier ASM,
1268 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001269 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1270 "Constant array of VLAs is illegal!");
1271
Chris Lattner38aeec72009-05-13 04:12:56 +00001272 // Convert the array size into a canonical width matching the pointer size for
1273 // the target.
1274 llvm::APInt ArySize(ArySizeIn);
1275 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1276
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001278 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001279
1280 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001281 if (ConstantArrayType *ATP =
1282 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 return QualType(ATP, 0);
1284
1285 // If the element type isn't canonical, this won't be a canonical type either,
1286 // so fill in the canonical type field.
1287 QualType Canonical;
1288 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001289 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001290 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001292 ConstantArrayType *NewIP =
1293 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001294 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 }
1296
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001297 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001298 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001299 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 Types.push_back(New);
1301 return QualType(New, 0);
1302}
1303
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001304/// getConstantArrayWithExprType - Return a reference to the type for
1305/// an array of the specified element type.
1306QualType
1307ASTContext::getConstantArrayWithExprType(QualType EltTy,
1308 const llvm::APInt &ArySizeIn,
1309 Expr *ArySizeExpr,
1310 ArrayType::ArraySizeModifier ASM,
1311 unsigned EltTypeQuals,
1312 SourceRange Brackets) {
1313 // Convert the array size into a canonical width matching the pointer
1314 // size for the target.
1315 llvm::APInt ArySize(ArySizeIn);
1316 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1317
1318 // Compute the canonical ConstantArrayType.
1319 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1320 ArySize, ASM, EltTypeQuals);
1321 // Since we don't unique expressions, it isn't possible to unique VLA's
1322 // that have an expression provided for their size.
1323 ConstantArrayWithExprType *New =
1324 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1325 ArySize, ArySizeExpr,
1326 ASM, EltTypeQuals, Brackets);
1327 Types.push_back(New);
1328 return QualType(New, 0);
1329}
1330
1331/// getConstantArrayWithoutExprType - Return a reference to the type for
1332/// an array of the specified element type.
1333QualType
1334ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1335 const llvm::APInt &ArySizeIn,
1336 ArrayType::ArraySizeModifier ASM,
1337 unsigned EltTypeQuals) {
1338 // Convert the array size into a canonical width matching the pointer
1339 // size for the target.
1340 llvm::APInt ArySize(ArySizeIn);
1341 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1342
1343 // Compute the canonical ConstantArrayType.
1344 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1345 ArySize, ASM, EltTypeQuals);
1346 ConstantArrayWithoutExprType *New =
1347 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1348 ArySize, ASM, EltTypeQuals);
1349 Types.push_back(New);
1350 return QualType(New, 0);
1351}
1352
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001353/// getVariableArrayType - Returns a non-unique reference to the type for a
1354/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001355QualType ASTContext::getVariableArrayType(QualType EltTy,
1356 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001357 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001358 unsigned EltTypeQuals,
1359 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001360 // Since we don't unique expressions, it isn't possible to unique VLA's
1361 // that have an expression provided for their size.
1362
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001363 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001364 new(*this,8)VariableArrayType(EltTy, QualType(),
1365 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001366
1367 VariableArrayTypes.push_back(New);
1368 Types.push_back(New);
1369 return QualType(New, 0);
1370}
1371
Douglas Gregor898574e2008-12-05 23:32:09 +00001372/// getDependentSizedArrayType - Returns a non-unique reference to
1373/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001374/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001375QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1376 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001377 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001378 unsigned EltTypeQuals,
1379 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001380 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1381 "Size must be type- or value-dependent!");
1382
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001383 llvm::FoldingSetNodeID ID;
1384 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1385 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001386
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001387 void *InsertPos = 0;
1388 DependentSizedArrayType *Canon
1389 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1390 DependentSizedArrayType *New;
1391 if (Canon) {
1392 // We already have a canonical version of this array type; use it as
1393 // the canonical type for a newly-built type.
1394 New = new (*this,8) DependentSizedArrayType(*this, EltTy,
1395 QualType(Canon, 0),
1396 NumElts, ASM, EltTypeQuals,
1397 Brackets);
1398 } else {
1399 QualType CanonEltTy = getCanonicalType(EltTy);
1400 if (CanonEltTy == EltTy) {
1401 New = new (*this,8) DependentSizedArrayType(*this, EltTy, QualType(),
1402 NumElts, ASM, EltTypeQuals,
1403 Brackets);
1404 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1405 } else {
1406 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1407 ASM, EltTypeQuals,
1408 SourceRange());
1409 New = new (*this,8) DependentSizedArrayType(*this, EltTy, Canon,
1410 NumElts, ASM, EltTypeQuals,
1411 Brackets);
1412 }
1413 }
1414
Douglas Gregor898574e2008-12-05 23:32:09 +00001415 Types.push_back(New);
1416 return QualType(New, 0);
1417}
1418
Eli Friedmanc5773c42008-02-15 18:16:39 +00001419QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1420 ArrayType::ArraySizeModifier ASM,
1421 unsigned EltTypeQuals) {
1422 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001423 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001424
1425 void *InsertPos = 0;
1426 if (IncompleteArrayType *ATP =
1427 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1428 return QualType(ATP, 0);
1429
1430 // If the element type isn't canonical, this won't be a canonical type
1431 // either, so fill in the canonical type field.
1432 QualType Canonical;
1433
1434 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001435 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001436 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001437
1438 // Get the new insert position for the node we care about.
1439 IncompleteArrayType *NewIP =
1440 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001441 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001442 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001443
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001444 IncompleteArrayType *New
1445 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1446 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001447
1448 IncompleteArrayTypes.InsertNode(New, InsertPos);
1449 Types.push_back(New);
1450 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001451}
1452
Steve Naroff73322922007-07-18 18:00:27 +00001453/// getVectorType - Return the unique reference to a vector type of
1454/// the specified element type and size. VectorType must be a built-in type.
1455QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 BuiltinType *baseType;
1457
Chris Lattnerf52ab252008-04-06 22:59:24 +00001458 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001459 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001460
1461 // Check if we've already instantiated a vector of this type.
1462 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001463 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 void *InsertPos = 0;
1465 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1466 return QualType(VTP, 0);
1467
1468 // If the element type isn't canonical, this won't be a canonical type either,
1469 // so fill in the canonical type field.
1470 QualType Canonical;
1471 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001472 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001473
1474 // Get the new insert position for the node we care about.
1475 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001476 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 }
Steve Narofff83820b2009-01-27 22:08:43 +00001478 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 VectorTypes.InsertNode(New, InsertPos);
1480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
Nate Begeman213541a2008-04-18 23:10:10 +00001484/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001485/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001486QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001487 BuiltinType *baseType;
1488
Chris Lattnerf52ab252008-04-06 22:59:24 +00001489 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001490 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001491
1492 // Check if we've already instantiated a vector of this type.
1493 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001494 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001495 void *InsertPos = 0;
1496 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1497 return QualType(VTP, 0);
1498
1499 // If the element type isn't canonical, this won't be a canonical type either,
1500 // so fill in the canonical type field.
1501 QualType Canonical;
1502 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001503 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001504
1505 // Get the new insert position for the node we care about.
1506 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001507 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001508 }
Steve Narofff83820b2009-01-27 22:08:43 +00001509 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001510 VectorTypes.InsertNode(New, InsertPos);
1511 Types.push_back(New);
1512 return QualType(New, 0);
1513}
1514
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001515QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1516 Expr *SizeExpr,
1517 SourceLocation AttrLoc) {
1518 DependentSizedExtVectorType *New =
1519 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1520 SizeExpr, AttrLoc);
1521
1522 DependentSizedExtVectorTypes.push_back(New);
1523 Types.push_back(New);
1524 return QualType(New, 0);
1525}
1526
Douglas Gregor72564e72009-02-26 23:50:07 +00001527/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001528///
Mike Stump24556362009-07-25 21:26:53 +00001529QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // Unique functions, to guarantee there is only one function of a particular
1531 // structure.
1532 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001533 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534
1535 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001536 if (FunctionNoProtoType *FT =
1537 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 return QualType(FT, 0);
1539
1540 QualType Canonical;
1541 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001542 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001543
1544 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001545 FunctionNoProtoType *NewIP =
1546 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001547 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 }
1549
Mike Stump24556362009-07-25 21:26:53 +00001550 FunctionNoProtoType *New
1551 = new (*this,8) FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001553 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 return QualType(New, 0);
1555}
1556
1557/// getFunctionType - Return a normal function type with a typed argument
1558/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001559QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001560 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001561 unsigned TypeQuals, bool hasExceptionSpec,
1562 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001563 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // Unique functions, to guarantee there is only one function of a particular
1565 // structure.
1566 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001567 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001568 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001569 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
1571 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001572 if (FunctionProtoType *FTP =
1573 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001575
1576 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001578 if (hasExceptionSpec)
1579 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1581 if (!ArgArray[i]->isCanonical())
1582 isCanonical = false;
1583
1584 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001585 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 QualType Canonical;
1587 if (!isCanonical) {
1588 llvm::SmallVector<QualType, 16> CanonicalArgs;
1589 CanonicalArgs.reserve(NumArgs);
1590 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001591 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001592
Chris Lattnerf52ab252008-04-06 22:59:24 +00001593 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001594 CanonicalArgs.data(), NumArgs,
Mike Stump24556362009-07-25 21:26:53 +00001595 isVariadic, TypeQuals, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001598 FunctionProtoType *NewIP =
1599 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001602
Douglas Gregor72564e72009-02-26 23:50:07 +00001603 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001604 // for two variable size arrays (for parameter and exception types) at the
1605 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001606 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001607 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1608 NumArgs*sizeof(QualType) +
1609 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001610 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001611 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001612 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001614 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 return QualType(FTP, 0);
1616}
1617
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001618/// getTypeDeclType - Return the unique reference to the type for the
1619/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001620QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001621 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001622 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1623
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001624 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001625 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001626 else if (isa<TemplateTypeParmDecl>(Decl)) {
1627 assert(false && "Template type parameter types are always available.");
1628 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001629 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001630
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001631 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001632 if (PrevDecl)
1633 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001634 else
1635 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001636 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001637 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1638 if (PrevDecl)
1639 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001640 else
1641 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001642 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001643 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001644 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001645
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001646 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001647 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001648}
1649
Reid Spencer5f016e22007-07-11 17:01:13 +00001650/// getTypedefType - Return the unique reference to the type for the
1651/// specified typename decl.
1652QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1653 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1654
Chris Lattnerf52ab252008-04-06 22:59:24 +00001655 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001656 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 Types.push_back(Decl->TypeForDecl);
1658 return QualType(Decl->TypeForDecl, 0);
1659}
1660
Douglas Gregorfab9d672009-02-05 23:33:38 +00001661/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001662/// parameter or parameter pack with the given depth, index, and (optionally)
1663/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001664QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001665 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001666 IdentifierInfo *Name) {
1667 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001668 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001669 void *InsertPos = 0;
1670 TemplateTypeParmType *TypeParm
1671 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1672
1673 if (TypeParm)
1674 return QualType(TypeParm, 0);
1675
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001676 if (Name) {
1677 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1678 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1679 Name, Canon);
1680 } else
1681 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001682
1683 Types.push_back(TypeParm);
1684 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1685
1686 return QualType(TypeParm, 0);
1687}
1688
Douglas Gregor55f6b142009-02-09 18:46:07 +00001689QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001690ASTContext::getTemplateSpecializationType(TemplateName Template,
1691 const TemplateArgument *Args,
1692 unsigned NumArgs,
1693 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001694 if (!Canon.isNull())
1695 Canon = getCanonicalType(Canon);
1696 else {
1697 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001698 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1699 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1700 CanonArgs.reserve(NumArgs);
1701 for (unsigned I = 0; I != NumArgs; ++I)
1702 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1703
1704 // Determine whether this canonical template specialization type already
1705 // exists.
1706 llvm::FoldingSetNodeID ID;
1707 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001708 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001709
1710 void *InsertPos = 0;
1711 TemplateSpecializationType *Spec
1712 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1713
1714 if (!Spec) {
1715 // Allocate a new canonical template specialization type.
1716 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1717 sizeof(TemplateArgument) * NumArgs),
1718 8);
Douglas Gregor828e2262009-07-29 16:09:57 +00001719 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001720 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001721 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001722 Types.push_back(Spec);
1723 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1724 }
1725
Douglas Gregorb88e8882009-07-30 17:40:51 +00001726 if (Canon.isNull())
1727 Canon = QualType(Spec, 0);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001728 assert(Canon->isDependentType() &&
1729 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001730 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001731
Douglas Gregor1275ae02009-07-28 23:00:59 +00001732 // Allocate the (non-canonical) template specialization type, but don't
1733 // try to unique it: these types typically have location information that
1734 // we don't unique and don't want to lose.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001735 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001736 sizeof(TemplateArgument) * NumArgs),
1737 8);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001738 TemplateSpecializationType *Spec
Douglas Gregor828e2262009-07-29 16:09:57 +00001739 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1740 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001741
Douglas Gregor55f6b142009-02-09 18:46:07 +00001742 Types.push_back(Spec);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001743 return QualType(Spec, 0);
1744}
1745
Douglas Gregore4e5b052009-03-19 00:18:19 +00001746QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001747ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001748 QualType NamedType) {
1749 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001750 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001751
1752 void *InsertPos = 0;
1753 QualifiedNameType *T
1754 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1755 if (T)
1756 return QualType(T, 0);
1757
Douglas Gregorab452ba2009-03-26 23:50:42 +00001758 T = new (*this) QualifiedNameType(NNS, NamedType,
1759 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001760 Types.push_back(T);
1761 QualifiedNameTypes.InsertNode(T, InsertPos);
1762 return QualType(T, 0);
1763}
1764
Douglas Gregord57959a2009-03-27 23:10:48 +00001765QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1766 const IdentifierInfo *Name,
1767 QualType Canon) {
1768 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1769
1770 if (Canon.isNull()) {
1771 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1772 if (CanonNNS != NNS)
1773 Canon = getTypenameType(CanonNNS, Name);
1774 }
1775
1776 llvm::FoldingSetNodeID ID;
1777 TypenameType::Profile(ID, NNS, Name);
1778
1779 void *InsertPos = 0;
1780 TypenameType *T
1781 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1782 if (T)
1783 return QualType(T, 0);
1784
1785 T = new (*this) TypenameType(NNS, Name, Canon);
1786 Types.push_back(T);
1787 TypenameTypes.InsertNode(T, InsertPos);
1788 return QualType(T, 0);
1789}
1790
Douglas Gregor17343172009-04-01 00:28:59 +00001791QualType
1792ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1793 const TemplateSpecializationType *TemplateId,
1794 QualType Canon) {
1795 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1796
1797 if (Canon.isNull()) {
1798 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1799 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1800 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1801 const TemplateSpecializationType *CanonTemplateId
1802 = CanonType->getAsTemplateSpecializationType();
1803 assert(CanonTemplateId &&
1804 "Canonical type must also be a template specialization type");
1805 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1806 }
1807 }
1808
1809 llvm::FoldingSetNodeID ID;
1810 TypenameType::Profile(ID, NNS, TemplateId);
1811
1812 void *InsertPos = 0;
1813 TypenameType *T
1814 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1815 if (T)
1816 return QualType(T, 0);
1817
1818 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1819 Types.push_back(T);
1820 TypenameTypes.InsertNode(T, InsertPos);
1821 return QualType(T, 0);
1822}
1823
Chris Lattner88cb27a2008-04-07 04:56:42 +00001824/// CmpProtocolNames - Comparison predicate for sorting protocols
1825/// alphabetically.
1826static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1827 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001828 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001829}
1830
1831static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1832 unsigned &NumProtocols) {
1833 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1834
1835 // Sort protocols, keyed by name.
1836 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1837
1838 // Remove duplicates.
1839 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1840 NumProtocols = ProtocolsEnd-Protocols;
1841}
1842
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001843/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1844/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001845QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001846 ObjCProtocolDecl **Protocols,
1847 unsigned NumProtocols) {
1848 // Sort the protocol list alphabetically to canonicalize it.
1849 if (NumProtocols)
1850 SortAndUniqueProtocols(Protocols, NumProtocols);
1851
1852 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001853 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001854
1855 void *InsertPos = 0;
1856 if (ObjCObjectPointerType *QT =
1857 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1858 return QualType(QT, 0);
1859
1860 // No Match;
1861 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001862 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001863
1864 Types.push_back(QType);
1865 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1866 return QualType(QType, 0);
1867}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001868
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001869/// getObjCInterfaceType - Return the unique reference to the type for the
1870/// specified ObjC interface decl. The list of protocols is optional.
1871QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001872 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001873 if (NumProtocols)
1874 // Sort the protocol list alphabetically to canonicalize it.
1875 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001876
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001877 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001878 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001879
1880 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001881 if (ObjCInterfaceType *QT =
1882 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001883 return QualType(QT, 0);
1884
1885 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001886 ObjCInterfaceType *QType =
1887 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1888 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001889 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001890 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001891 return QualType(QType, 0);
1892}
1893
Douglas Gregor72564e72009-02-26 23:50:07 +00001894/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1895/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001896/// multiple declarations that refer to "typeof(x)" all contain different
1897/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1898/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001899QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001900 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00001901 if (tofExpr->isTypeDependent()) {
1902 llvm::FoldingSetNodeID ID;
1903 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
1904
1905 void *InsertPos = 0;
1906 DependentTypeOfExprType *Canon
1907 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
1908 if (Canon) {
1909 // We already have a "canonical" version of an identical, dependent
1910 // typeof(expr) type. Use that as our canonical type.
1911 toe = new (*this, 8) TypeOfExprType(tofExpr,
1912 QualType((TypeOfExprType*)Canon, 0));
1913 }
1914 else {
1915 // Build a new, canonical typeof(expr) type.
1916 Canon = new (*this, 8) DependentTypeOfExprType(*this, tofExpr);
1917 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
1918 toe = Canon;
1919 }
1920 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001921 QualType Canonical = getCanonicalType(tofExpr->getType());
1922 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1923 }
Steve Naroff9752f252007-08-01 18:02:17 +00001924 Types.push_back(toe);
1925 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001926}
1927
Steve Naroff9752f252007-08-01 18:02:17 +00001928/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1929/// TypeOfType AST's. The only motivation to unique these nodes would be
1930/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1931/// an issue. This doesn't effect the type checker, since it operates
1932/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001933QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001934 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001935 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001936 Types.push_back(tot);
1937 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001938}
1939
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001940/// getDecltypeForExpr - Given an expr, will return the decltype for that
1941/// expression, according to the rules in C++0x [dcl.type.simple]p4
1942static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001943 if (e->isTypeDependent())
1944 return Context.DependentTy;
1945
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001946 // If e is an id expression or a class member access, decltype(e) is defined
1947 // as the type of the entity named by e.
1948 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1949 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1950 return VD->getType();
1951 }
1952 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1953 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1954 return FD->getType();
1955 }
1956 // If e is a function call or an invocation of an overloaded operator,
1957 // (parentheses around e are ignored), decltype(e) is defined as the
1958 // return type of that function.
1959 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1960 return CE->getCallReturnType();
1961
1962 QualType T = e->getType();
1963
1964 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1965 // defined as T&, otherwise decltype(e) is defined as T.
1966 if (e->isLvalue(Context) == Expr::LV_Valid)
1967 T = Context.getLValueReferenceType(T);
1968
1969 return T;
1970}
1971
Anders Carlsson395b4752009-06-24 19:06:50 +00001972/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1973/// DecltypeType AST's. The only motivation to unique these nodes would be
1974/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1975/// an issue. This doesn't effect the type checker, since it operates
1976/// on canonical type's (which are always unique).
1977QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001978 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00001979 if (e->isTypeDependent()) {
1980 llvm::FoldingSetNodeID ID;
1981 DependentDecltypeType::Profile(ID, *this, e);
1982
1983 void *InsertPos = 0;
1984 DependentDecltypeType *Canon
1985 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
1986 if (Canon) {
1987 // We already have a "canonical" version of an equivalent, dependent
1988 // decltype type. Use that as our canonical type.
1989 dt = new (*this, 8) DecltypeType(e, DependentTy,
1990 QualType((DecltypeType*)Canon, 0));
1991 }
1992 else {
1993 // Build a new, canonical typeof(expr) type.
1994 Canon = new (*this, 8) DependentDecltypeType(*this, e);
1995 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
1996 dt = Canon;
1997 }
1998 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001999 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00002000 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002001 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002002 Types.push_back(dt);
2003 return QualType(dt, 0);
2004}
2005
Reid Spencer5f016e22007-07-11 17:01:13 +00002006/// getTagDeclType - Return the unique reference to the type for the
2007/// specified TagDecl (struct/union/class/enum) decl.
2008QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002009 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002010 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002011}
2012
2013/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2014/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2015/// needs to agree with the definition in <stddef.h>.
2016QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002017 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002018}
2019
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002020/// getSignedWCharType - Return the type of "signed wchar_t".
2021/// Used when in C++, as a GCC extension.
2022QualType ASTContext::getSignedWCharType() const {
2023 // FIXME: derive from "Target" ?
2024 return WCharTy;
2025}
2026
2027/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2028/// Used when in C++, as a GCC extension.
2029QualType ASTContext::getUnsignedWCharType() const {
2030 // FIXME: derive from "Target" ?
2031 return UnsignedIntTy;
2032}
2033
Chris Lattner8b9023b2007-07-13 03:05:23 +00002034/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2035/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2036QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002037 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002038}
2039
Chris Lattnere6327742008-04-02 05:18:44 +00002040//===----------------------------------------------------------------------===//
2041// Type Operators
2042//===----------------------------------------------------------------------===//
2043
Chris Lattner77c96472008-04-06 22:41:35 +00002044/// getCanonicalType - Return the canonical (structural) type corresponding to
2045/// the specified potentially non-canonical type. The non-canonical version
2046/// of a type may have many "decorated" versions of types. Decorators can
2047/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2048/// to be free of any of these, allowing two canonical types to be compared
2049/// for exact equality with a simple pointer comparison.
2050QualType ASTContext::getCanonicalType(QualType T) {
2051 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002052
2053 // If the result has type qualifiers, make sure to canonicalize them as well.
2054 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2055 if (TypeQuals == 0) return CanType;
2056
2057 // If the type qualifiers are on an array type, get the canonical type of the
2058 // array with the qualifiers applied to the element type.
2059 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2060 if (!AT)
2061 return CanType.getQualifiedType(TypeQuals);
2062
2063 // Get the canonical version of the element with the extra qualifiers on it.
2064 // This can recursively sink qualifiers through multiple levels of arrays.
2065 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2066 NewEltTy = getCanonicalType(NewEltTy);
2067
2068 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2069 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2070 CAT->getIndexTypeQualifier());
2071 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2072 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2073 IAT->getIndexTypeQualifier());
2074
Douglas Gregor898574e2008-12-05 23:32:09 +00002075 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002076 return getDependentSizedArrayType(NewEltTy,
2077 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002078 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002079 DSAT->getIndexTypeQualifier(),
2080 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002081
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002082 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002083 return getVariableArrayType(NewEltTy,
2084 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002085 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002086 VAT->getIndexTypeQualifier(),
2087 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002088}
2089
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002090TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2091 // If this template name refers to a template, the canonical
2092 // template name merely stores the template itself.
2093 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002094 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002095
Douglas Gregord99cbe62009-07-29 18:26:50 +00002096 // If this template name refers to a set of overloaded function templates,
2097 /// the canonical template name merely stores the set of function templates.
2098 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl())
2099 // FIXME: Can't really canonicalize a set of overloaded functions, can we?
2100 return TemplateName(Ovl);
2101
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002102 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2103 assert(DTN && "Non-dependent template names must refer to template decls.");
2104 return DTN->CanonicalTemplateName;
2105}
2106
Douglas Gregor1275ae02009-07-28 23:00:59 +00002107TemplateArgument
2108ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2109 switch (Arg.getKind()) {
2110 case TemplateArgument::Null:
2111 return Arg;
2112
2113 case TemplateArgument::Expression:
2114 // FIXME: Build canonical expression?
2115 return Arg;
2116
2117 case TemplateArgument::Declaration:
2118 return TemplateArgument(SourceLocation(),
2119 Arg.getAsDecl()->getCanonicalDecl());
2120
2121 case TemplateArgument::Integral:
2122 return TemplateArgument(SourceLocation(),
2123 *Arg.getAsIntegral(),
2124 getCanonicalType(Arg.getIntegralType()));
2125
2126 case TemplateArgument::Type:
2127 return TemplateArgument(SourceLocation(),
2128 getCanonicalType(Arg.getAsType()));
2129
2130 case TemplateArgument::Pack: {
2131 // FIXME: Allocate in ASTContext
2132 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2133 unsigned Idx = 0;
2134 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2135 AEnd = Arg.pack_end();
2136 A != AEnd; (void)++A, ++Idx)
2137 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2138
2139 TemplateArgument Result;
2140 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2141 return Result;
2142 }
2143 }
2144
2145 // Silence GCC warning
2146 assert(false && "Unhandled template argument kind");
2147 return TemplateArgument();
2148}
2149
Douglas Gregord57959a2009-03-27 23:10:48 +00002150NestedNameSpecifier *
2151ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2152 if (!NNS)
2153 return 0;
2154
2155 switch (NNS->getKind()) {
2156 case NestedNameSpecifier::Identifier:
2157 // Canonicalize the prefix but keep the identifier the same.
2158 return NestedNameSpecifier::Create(*this,
2159 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2160 NNS->getAsIdentifier());
2161
2162 case NestedNameSpecifier::Namespace:
2163 // A namespace is canonical; build a nested-name-specifier with
2164 // this namespace and no prefix.
2165 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2166
2167 case NestedNameSpecifier::TypeSpec:
2168 case NestedNameSpecifier::TypeSpecWithTemplate: {
2169 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2170 NestedNameSpecifier *Prefix = 0;
2171
2172 // FIXME: This isn't the right check!
2173 if (T->isDependentType())
2174 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2175
2176 return NestedNameSpecifier::Create(*this, Prefix,
2177 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2178 T.getTypePtr());
2179 }
2180
2181 case NestedNameSpecifier::Global:
2182 // The global specifier is canonical and unique.
2183 return NNS;
2184 }
2185
2186 // Required to silence a GCC warning
2187 return 0;
2188}
2189
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002190
2191const ArrayType *ASTContext::getAsArrayType(QualType T) {
2192 // Handle the non-qualified case efficiently.
2193 if (T.getCVRQualifiers() == 0) {
2194 // Handle the common positive case fast.
2195 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2196 return AT;
2197 }
2198
2199 // Handle the common negative case fast, ignoring CVR qualifiers.
2200 QualType CType = T->getCanonicalTypeInternal();
2201
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002202 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002203 // test.
2204 if (!isa<ArrayType>(CType) &&
2205 !isa<ArrayType>(CType.getUnqualifiedType()))
2206 return 0;
2207
2208 // Apply any CVR qualifiers from the array type to the element type. This
2209 // implements C99 6.7.3p8: "If the specification of an array type includes
2210 // any type qualifiers, the element type is so qualified, not the array type."
2211
2212 // If we get here, we either have type qualifiers on the type, or we have
2213 // sugar such as a typedef in the way. If we have type qualifiers on the type
2214 // we must propagate them down into the elemeng type.
2215 unsigned CVRQuals = T.getCVRQualifiers();
2216 unsigned AddrSpace = 0;
2217 Type *Ty = T.getTypePtr();
2218
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002219 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002220 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002221 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2222 AddrSpace = EXTQT->getAddressSpace();
2223 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002224 } else {
2225 T = Ty->getDesugaredType();
2226 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2227 break;
2228 CVRQuals |= T.getCVRQualifiers();
2229 Ty = T.getTypePtr();
2230 }
2231 }
2232
2233 // If we have a simple case, just return now.
2234 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2235 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2236 return ATy;
2237
2238 // Otherwise, we have an array and we have qualifiers on it. Push the
2239 // qualifiers into the array element type and return a new array type.
2240 // Get the canonical version of the element with the extra qualifiers on it.
2241 // This can recursively sink qualifiers through multiple levels of arrays.
2242 QualType NewEltTy = ATy->getElementType();
2243 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002244 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002245 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2246
2247 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2248 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2249 CAT->getSizeModifier(),
2250 CAT->getIndexTypeQualifier()));
2251 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2252 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2253 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002254 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002255
Douglas Gregor898574e2008-12-05 23:32:09 +00002256 if (const DependentSizedArrayType *DSAT
2257 = dyn_cast<DependentSizedArrayType>(ATy))
2258 return cast<ArrayType>(
2259 getDependentSizedArrayType(NewEltTy,
2260 DSAT->getSizeExpr(),
2261 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002262 DSAT->getIndexTypeQualifier(),
2263 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002264
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002265 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002266 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2267 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002268 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002269 VAT->getIndexTypeQualifier(),
2270 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002271}
2272
2273
Chris Lattnere6327742008-04-02 05:18:44 +00002274/// getArrayDecayedType - Return the properly qualified result of decaying the
2275/// specified array type to a pointer. This operation is non-trivial when
2276/// handling typedefs etc. The canonical type of "T" must be an array type,
2277/// this returns a pointer to a properly qualified element of the array.
2278///
2279/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2280QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002281 // Get the element type with 'getAsArrayType' so that we don't lose any
2282 // typedefs in the element type of the array. This also handles propagation
2283 // of type qualifiers from the array type into the element type if present
2284 // (C99 6.7.3p8).
2285 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2286 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002287
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002288 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002289
2290 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002291 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002292}
2293
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002294QualType ASTContext::getBaseElementType(QualType QT) {
2295 QualifierSet qualifiers;
2296 while (true) {
2297 const Type *UT = qualifiers.strip(QT);
2298 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2299 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002300 } else {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002301 return qualifiers.apply(QT, *this);
2302 }
2303 }
2304}
2305
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002306QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002307 QualType ElemTy = VAT->getElementType();
2308
2309 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2310 return getBaseElementType(VAT);
2311
2312 return ElemTy;
2313}
2314
Reid Spencer5f016e22007-07-11 17:01:13 +00002315/// getFloatingRank - Return a relative rank for floating point types.
2316/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002317static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002318 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002320
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002321 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002322 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002323 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 case BuiltinType::Float: return FloatRank;
2325 case BuiltinType::Double: return DoubleRank;
2326 case BuiltinType::LongDouble: return LongDoubleRank;
2327 }
2328}
2329
Steve Naroff716c7302007-08-27 01:41:48 +00002330/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2331/// point or a complex type (based on typeDomain/typeSize).
2332/// 'typeDomain' is a real floating point or complex type.
2333/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002334QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2335 QualType Domain) const {
2336 FloatingRank EltRank = getFloatingRank(Size);
2337 if (Domain->isComplexType()) {
2338 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002339 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002340 case FloatRank: return FloatComplexTy;
2341 case DoubleRank: return DoubleComplexTy;
2342 case LongDoubleRank: return LongDoubleComplexTy;
2343 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 }
Chris Lattner1361b112008-04-06 23:58:54 +00002345
2346 assert(Domain->isRealFloatingType() && "Unknown domain!");
2347 switch (EltRank) {
2348 default: assert(0 && "getFloatingRank(): illegal value for rank");
2349 case FloatRank: return FloatTy;
2350 case DoubleRank: return DoubleTy;
2351 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002352 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002353}
2354
Chris Lattner7cfeb082008-04-06 23:55:33 +00002355/// getFloatingTypeOrder - Compare the rank of the two specified floating
2356/// point types, ignoring the domain of the type (i.e. 'double' ==
2357/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2358/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002359int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2360 FloatingRank LHSR = getFloatingRank(LHS);
2361 FloatingRank RHSR = getFloatingRank(RHS);
2362
2363 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002364 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002365 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002366 return 1;
2367 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002368}
2369
Chris Lattnerf52ab252008-04-06 22:59:24 +00002370/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2371/// routine will assert if passed a built-in type that isn't an integer or enum,
2372/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002373unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002374 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002375 if (EnumType* ET = dyn_cast<EnumType>(T))
2376 T = ET->getDecl()->getIntegerType().getTypePtr();
2377
Eli Friedmana3426752009-07-05 23:44:27 +00002378 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2379 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2380
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002381 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2382 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2383
2384 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2385 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2386
Eli Friedmanf98aba32009-02-13 02:31:07 +00002387 // There are two things which impact the integer rank: the width, and
2388 // the ordering of builtins. The builtin ordering is encoded in the
2389 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002390 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002391 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002392
Chris Lattnerf52ab252008-04-06 22:59:24 +00002393 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002394 default: assert(0 && "getIntegerRank(): not a built-in integer");
2395 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002396 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002397 case BuiltinType::Char_S:
2398 case BuiltinType::Char_U:
2399 case BuiltinType::SChar:
2400 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002401 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002402 case BuiltinType::Short:
2403 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002404 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002405 case BuiltinType::Int:
2406 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002407 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002408 case BuiltinType::Long:
2409 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002410 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002411 case BuiltinType::LongLong:
2412 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002413 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002414 case BuiltinType::Int128:
2415 case BuiltinType::UInt128:
2416 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002417 }
2418}
2419
Chris Lattner7cfeb082008-04-06 23:55:33 +00002420/// getIntegerTypeOrder - Returns the highest ranked integer type:
2421/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2422/// LHS < RHS, return -1.
2423int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002424 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2425 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002426 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002427
Chris Lattnerf52ab252008-04-06 22:59:24 +00002428 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2429 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002430
Chris Lattner7cfeb082008-04-06 23:55:33 +00002431 unsigned LHSRank = getIntegerRank(LHSC);
2432 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002433
Chris Lattner7cfeb082008-04-06 23:55:33 +00002434 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2435 if (LHSRank == RHSRank) return 0;
2436 return LHSRank > RHSRank ? 1 : -1;
2437 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002438
Chris Lattner7cfeb082008-04-06 23:55:33 +00002439 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2440 if (LHSUnsigned) {
2441 // If the unsigned [LHS] type is larger, return it.
2442 if (LHSRank >= RHSRank)
2443 return 1;
2444
2445 // If the signed type can represent all values of the unsigned type, it
2446 // wins. Because we are dealing with 2's complement and types that are
2447 // powers of two larger than each other, this is always safe.
2448 return -1;
2449 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002450
Chris Lattner7cfeb082008-04-06 23:55:33 +00002451 // If the unsigned [RHS] type is larger, return it.
2452 if (RHSRank >= LHSRank)
2453 return -1;
2454
2455 // If the signed type can represent all values of the unsigned type, it
2456 // wins. Because we are dealing with 2's complement and types that are
2457 // powers of two larger than each other, this is always safe.
2458 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002459}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002460
2461// getCFConstantStringType - Return the type used for constant CFStrings.
2462QualType ASTContext::getCFConstantStringType() {
2463 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002464 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002465 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002466 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002467 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002468
2469 // const int *isa;
2470 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002471 // int flags;
2472 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002473 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002474 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002475 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002476 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002477
Anders Carlsson71993dd2007-08-17 05:31:46 +00002478 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002479 for (unsigned i = 0; i < 4; ++i) {
2480 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2481 SourceLocation(), 0,
2482 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002483 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002484 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002485 }
2486
2487 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002488 }
2489
2490 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002491}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002492
Douglas Gregor319ac892009-04-23 22:29:11 +00002493void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002494 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002495 assert(Rec && "Invalid CFConstantStringType");
2496 CFConstantStringTypeDecl = Rec->getDecl();
2497}
2498
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002499QualType ASTContext::getObjCFastEnumerationStateType()
2500{
2501 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002502 ObjCFastEnumerationStateTypeDecl =
2503 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2504 &Idents.get("__objcFastEnumerationState"));
2505
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002506 QualType FieldTypes[] = {
2507 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002508 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002509 getPointerType(UnsignedLongTy),
2510 getConstantArrayType(UnsignedLongTy,
2511 llvm::APInt(32, 5), ArrayType::Normal, 0)
2512 };
2513
Douglas Gregor44b43212008-12-11 16:49:14 +00002514 for (size_t i = 0; i < 4; ++i) {
2515 FieldDecl *Field = FieldDecl::Create(*this,
2516 ObjCFastEnumerationStateTypeDecl,
2517 SourceLocation(), 0,
2518 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002519 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002520 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002521 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002522
Douglas Gregor44b43212008-12-11 16:49:14 +00002523 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002524 }
2525
2526 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2527}
2528
Douglas Gregor319ac892009-04-23 22:29:11 +00002529void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002530 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002531 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2532 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2533}
2534
Anders Carlssone8c49532007-10-29 06:33:42 +00002535// This returns true if a type has been typedefed to BOOL:
2536// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002537static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002538 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002539 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2540 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002541
2542 return false;
2543}
2544
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002546/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002547int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002548 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002549
2550 // Make all integer and enum types at least as large as an int
2551 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002552 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002553 // Treat arrays as pointers, since that's how they're passed in.
2554 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002555 sz = getTypeSize(VoidPtrTy);
2556 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002557}
2558
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002559/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002560/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002561void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002562 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002563 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002564 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002566 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002567 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002568 // Compute size of all parameters.
2569 // Start with computing size of a pointer in number of bytes.
2570 // FIXME: There might(should) be a better way of doing this computation!
2571 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002572 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002573 // The first two arguments (self and _cmd) are pointers; account for
2574 // their size.
2575 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002576 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2577 E = Decl->param_end(); PI != E; ++PI) {
2578 QualType PType = (*PI)->getType();
2579 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002580 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002581 ParmOffset += sz;
2582 }
2583 S += llvm::utostr(ParmOffset);
2584 S += "@0:";
2585 S += llvm::utostr(PtrSize);
2586
2587 // Argument types.
2588 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002589 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2590 E = Decl->param_end(); PI != E; ++PI) {
2591 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002592 QualType PType = PVDecl->getOriginalType();
2593 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002594 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2595 // Use array's original type only if it has known number of
2596 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002597 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002598 PType = PVDecl->getType();
2599 } else if (PType->isFunctionType())
2600 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002601 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002602 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002603 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002604 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002605 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002606 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002607 }
2608}
2609
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002610/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002611/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002612/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2613/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002614/// Property attributes are stored as a comma-delimited C string. The simple
2615/// attributes readonly and bycopy are encoded as single characters. The
2616/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2617/// encoded as single characters, followed by an identifier. Property types
2618/// are also encoded as a parametrized attribute. The characters used to encode
2619/// these attributes are defined by the following enumeration:
2620/// @code
2621/// enum PropertyAttributes {
2622/// kPropertyReadOnly = 'R', // property is read-only.
2623/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2624/// kPropertyByref = '&', // property is a reference to the value last assigned
2625/// kPropertyDynamic = 'D', // property is dynamic
2626/// kPropertyGetter = 'G', // followed by getter selector name
2627/// kPropertySetter = 'S', // followed by setter selector name
2628/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2629/// kPropertyType = 't' // followed by old-style type encoding.
2630/// kPropertyWeak = 'W' // 'weak' property
2631/// kPropertyStrong = 'P' // property GC'able
2632/// kPropertyNonAtomic = 'N' // property non-atomic
2633/// };
2634/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002635void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2636 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002637 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002638 // Collect information from the property implementation decl(s).
2639 bool Dynamic = false;
2640 ObjCPropertyImplDecl *SynthesizePID = 0;
2641
2642 // FIXME: Duplicated code due to poor abstraction.
2643 if (Container) {
2644 if (const ObjCCategoryImplDecl *CID =
2645 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2646 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002647 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002648 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002649 ObjCPropertyImplDecl *PID = *i;
2650 if (PID->getPropertyDecl() == PD) {
2651 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2652 Dynamic = true;
2653 } else {
2654 SynthesizePID = PID;
2655 }
2656 }
2657 }
2658 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002659 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002660 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002661 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002662 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002663 ObjCPropertyImplDecl *PID = *i;
2664 if (PID->getPropertyDecl() == PD) {
2665 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2666 Dynamic = true;
2667 } else {
2668 SynthesizePID = PID;
2669 }
2670 }
2671 }
2672 }
2673 }
2674
2675 // FIXME: This is not very efficient.
2676 S = "T";
2677
2678 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002679 // GCC has some special rules regarding encoding of properties which
2680 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002681 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002682 true /* outermost type */,
2683 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002684
2685 if (PD->isReadOnly()) {
2686 S += ",R";
2687 } else {
2688 switch (PD->getSetterKind()) {
2689 case ObjCPropertyDecl::Assign: break;
2690 case ObjCPropertyDecl::Copy: S += ",C"; break;
2691 case ObjCPropertyDecl::Retain: S += ",&"; break;
2692 }
2693 }
2694
2695 // It really isn't clear at all what this means, since properties
2696 // are "dynamic by default".
2697 if (Dynamic)
2698 S += ",D";
2699
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002700 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2701 S += ",N";
2702
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002703 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2704 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002705 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002706 }
2707
2708 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2709 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002710 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002711 }
2712
2713 if (SynthesizePID) {
2714 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2715 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002716 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002717 }
2718
2719 // FIXME: OBJCGC: weak & strong
2720}
2721
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002722/// getLegacyIntegralTypeEncoding -
2723/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002724/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002725/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2726///
2727void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00002728 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002729 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002730 if (BT->getKind() == BuiltinType::ULong &&
2731 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002732 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002733 else
2734 if (BT->getKind() == BuiltinType::Long &&
2735 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002736 PointeeTy = IntTy;
2737 }
2738 }
2739}
2740
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002741void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002742 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002743 // We follow the behavior of gcc, expanding structures which are
2744 // directly pointed to, and expanding embedded structures. Note that
2745 // these rules are sufficient to prevent recursive encoding of the
2746 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002747 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2748 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002749}
2750
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002751static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002752 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002753 const Expr *E = FD->getBitWidth();
2754 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2755 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002756 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002757 S += 'b';
2758 S += llvm::utostr(N);
2759}
2760
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002761void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2762 bool ExpandPointedToStructures,
2763 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002764 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002765 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002766 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002767 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002768 if (FD && FD->isBitField())
2769 return EncodeBitField(this, S, FD);
2770 char encoding;
2771 switch (BT->getKind()) {
2772 default: assert(0 && "Unhandled builtin type kind");
2773 case BuiltinType::Void: encoding = 'v'; break;
2774 case BuiltinType::Bool: encoding = 'B'; break;
2775 case BuiltinType::Char_U:
2776 case BuiltinType::UChar: encoding = 'C'; break;
2777 case BuiltinType::UShort: encoding = 'S'; break;
2778 case BuiltinType::UInt: encoding = 'I'; break;
2779 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002780 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002781 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002782 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002783 case BuiltinType::UInt128: encoding = 'T'; break;
2784 case BuiltinType::ULongLong: encoding = 'Q'; break;
2785 case BuiltinType::Char_S:
2786 case BuiltinType::SChar: encoding = 'c'; break;
2787 case BuiltinType::Short: encoding = 's'; break;
2788 case BuiltinType::Int: encoding = 'i'; break;
2789 case BuiltinType::Long:
2790 encoding =
2791 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2792 break;
2793 case BuiltinType::LongLong: encoding = 'q'; break;
2794 case BuiltinType::Int128: encoding = 't'; break;
2795 case BuiltinType::Float: encoding = 'f'; break;
2796 case BuiltinType::Double: encoding = 'd'; break;
2797 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002798 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002799
2800 S += encoding;
2801 return;
2802 }
2803
2804 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002805 S += 'j';
2806 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2807 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002808 return;
2809 }
2810
Ted Kremenek6217b802009-07-29 21:53:49 +00002811 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002812 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002813 bool isReadOnly = false;
2814 // For historical/compatibility reasons, the read-only qualifier of the
2815 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2816 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2817 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00002818 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002819 if (OutermostType && T.isConstQualified()) {
2820 isReadOnly = true;
2821 S += 'r';
2822 }
2823 }
2824 else if (OutermostType) {
2825 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002826 while (P->getAs<PointerType>())
2827 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002828 if (P.isConstQualified()) {
2829 isReadOnly = true;
2830 S += 'r';
2831 }
2832 }
2833 if (isReadOnly) {
2834 // Another legacy compatibility encoding. Some ObjC qualifier and type
2835 // combinations need to be rearranged.
2836 // Rewrite "in const" from "nr" to "rn"
2837 const char * s = S.c_str();
2838 int len = S.length();
2839 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2840 std::string replace = "rn";
2841 S.replace(S.end()-2, S.end(), replace);
2842 }
2843 }
Steve Naroff14108da2009-07-10 23:34:53 +00002844 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002845 S += ':';
2846 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002847 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002848
2849 if (PointeeTy->isCharType()) {
2850 // char pointer types should be encoded as '*' unless it is a
2851 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002852 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002853 S += '*';
2854 return;
2855 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002856 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00002857 // GCC binary compat: Need to convert "struct objc_class *" to "#".
2858 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2859 S += '#';
2860 return;
2861 }
2862 // GCC binary compat: Need to convert "struct objc_object *" to "@".
2863 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2864 S += '@';
2865 return;
2866 }
2867 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002868 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002869 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002870 getLegacyIntegralTypeEncoding(PointeeTy);
2871
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002872 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002873 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002874 return;
2875 }
2876
2877 if (const ArrayType *AT =
2878 // Ignore type qualifiers etc.
2879 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002880 if (isa<IncompleteArrayType>(AT)) {
2881 // Incomplete arrays are encoded as a pointer to the array element.
2882 S += '^';
2883
2884 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2885 false, ExpandStructures, FD);
2886 } else {
2887 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002888
Anders Carlsson559a8332009-02-22 01:38:57 +00002889 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2890 S += llvm::utostr(CAT->getSize().getZExtValue());
2891 else {
2892 //Variable length arrays are encoded as a regular array with 0 elements.
2893 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2894 S += '0';
2895 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002896
Anders Carlsson559a8332009-02-22 01:38:57 +00002897 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2898 false, ExpandStructures, FD);
2899 S += ']';
2900 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002901 return;
2902 }
2903
2904 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002905 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002906 return;
2907 }
2908
Ted Kremenek6217b802009-07-29 21:53:49 +00002909 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002910 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002911 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002912 // Anonymous structures print as '?'
2913 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2914 S += II->getName();
2915 } else {
2916 S += '?';
2917 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002918 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002919 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002920 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2921 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002922 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002923 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002924 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002925 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002926 S += '"';
2927 }
2928
2929 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002930 if (Field->isBitField()) {
2931 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2932 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002933 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002934 QualType qt = Field->getType();
2935 getLegacyIntegralTypeEncoding(qt);
2936 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002937 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002938 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002939 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002940 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002941 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002942 return;
2943 }
2944
2945 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002946 if (FD && FD->isBitField())
2947 EncodeBitField(this, S, FD);
2948 else
2949 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002950 return;
2951 }
2952
2953 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002954 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002955 return;
2956 }
2957
2958 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002959 // @encode(class_name)
2960 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2961 S += '{';
2962 const IdentifierInfo *II = OI->getIdentifier();
2963 S += II->getName();
2964 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002965 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002966 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002967 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002968 if (RecFields[i]->isBitField())
2969 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2970 RecFields[i]);
2971 else
2972 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2973 FD);
2974 }
2975 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002976 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002977 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002978
2979 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002980 if (OPT->isObjCIdType()) {
2981 S += '@';
2982 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002983 }
2984
2985 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002986 S += '#';
2987 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002988 }
2989
2990 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002991 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2992 ExpandPointedToStructures,
2993 ExpandStructures, FD);
2994 if (FD || EncodingProperty) {
2995 // Note that we do extended encoding of protocol qualifer list
2996 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00002997 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002998 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2999 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003000 S += '<';
3001 S += (*I)->getNameAsString();
3002 S += '>';
3003 }
3004 S += '"';
3005 }
3006 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003007 }
3008
3009 QualType PointeeTy = OPT->getPointeeType();
3010 if (!EncodingProperty &&
3011 isa<TypedefType>(PointeeTy.getTypePtr())) {
3012 // Another historical/compatibility reason.
3013 // We encode the underlying type which comes out as
3014 // {...};
3015 S += '^';
3016 getObjCEncodingForTypeImpl(PointeeTy, S,
3017 false, ExpandPointedToStructures,
3018 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003019 return;
3020 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003021
3022 S += '@';
3023 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003024 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003025 S += OPT->getInterfaceDecl()->getNameAsCString();
3026 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3027 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003028 S += '<';
3029 S += (*I)->getNameAsString();
3030 S += '>';
3031 }
3032 S += '"';
3033 }
3034 return;
3035 }
3036
3037 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003038}
3039
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003040void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003041 std::string& S) const {
3042 if (QT & Decl::OBJC_TQ_In)
3043 S += 'n';
3044 if (QT & Decl::OBJC_TQ_Inout)
3045 S += 'N';
3046 if (QT & Decl::OBJC_TQ_Out)
3047 S += 'o';
3048 if (QT & Decl::OBJC_TQ_Bycopy)
3049 S += 'O';
3050 if (QT & Decl::OBJC_TQ_Byref)
3051 S += 'R';
3052 if (QT & Decl::OBJC_TQ_Oneway)
3053 S += 'V';
3054}
3055
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003056void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003057 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3058
3059 BuiltinVaListType = T;
3060}
3061
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003062void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003063 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003064}
3065
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003066void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003067 ObjCSelType = T;
3068
3069 const TypedefType *TT = T->getAsTypedefType();
3070 if (!TT)
3071 return;
3072 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003073
3074 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003075 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003076 if (!ptr)
3077 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003078 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003079 if (!rec)
3080 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003081 SelStructType = rec;
3082}
3083
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003084void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003086}
3087
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003088void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003089 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003090}
3091
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003092void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3093 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003094 "'NSConstantString' type already set!");
3095
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003096 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003097}
3098
Douglas Gregor7532dc62009-03-30 22:58:21 +00003099/// \brief Retrieve the template name that represents a qualified
3100/// template name such as \c std::vector.
3101TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3102 bool TemplateKeyword,
3103 TemplateDecl *Template) {
3104 llvm::FoldingSetNodeID ID;
3105 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3106
3107 void *InsertPos = 0;
3108 QualifiedTemplateName *QTN =
3109 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3110 if (!QTN) {
3111 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3112 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3113 }
3114
3115 return TemplateName(QTN);
3116}
3117
Douglas Gregord99cbe62009-07-29 18:26:50 +00003118/// \brief Retrieve the template name that represents a qualified
3119/// template name such as \c std::vector.
3120TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3121 bool TemplateKeyword,
3122 OverloadedFunctionDecl *Template) {
3123 llvm::FoldingSetNodeID ID;
3124 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3125
3126 void *InsertPos = 0;
3127 QualifiedTemplateName *QTN =
3128 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3129 if (!QTN) {
3130 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3131 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3132 }
3133
3134 return TemplateName(QTN);
3135}
3136
Douglas Gregor7532dc62009-03-30 22:58:21 +00003137/// \brief Retrieve the template name that represents a dependent
3138/// template name such as \c MetaFun::template apply.
3139TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3140 const IdentifierInfo *Name) {
3141 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3142
3143 llvm::FoldingSetNodeID ID;
3144 DependentTemplateName::Profile(ID, NNS, Name);
3145
3146 void *InsertPos = 0;
3147 DependentTemplateName *QTN =
3148 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3149
3150 if (QTN)
3151 return TemplateName(QTN);
3152
3153 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3154 if (CanonNNS == NNS) {
3155 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3156 } else {
3157 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3158 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3159 }
3160
3161 DependentTemplateNames.InsertNode(QTN, InsertPos);
3162 return TemplateName(QTN);
3163}
3164
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003165/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003166/// TargetInfo, produce the corresponding type. The unsigned @p Type
3167/// is actually a value of type @c TargetInfo::IntType.
3168QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003169 switch (Type) {
3170 case TargetInfo::NoInt: return QualType();
3171 case TargetInfo::SignedShort: return ShortTy;
3172 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3173 case TargetInfo::SignedInt: return IntTy;
3174 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3175 case TargetInfo::SignedLong: return LongTy;
3176 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3177 case TargetInfo::SignedLongLong: return LongLongTy;
3178 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3179 }
3180
3181 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003182 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003183}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003184
3185//===----------------------------------------------------------------------===//
3186// Type Predicates.
3187//===----------------------------------------------------------------------===//
3188
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003189/// isObjCNSObjectType - Return true if this is an NSObject object using
3190/// NSObject attribute on a c-style pointer type.
3191/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003192/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003193///
3194bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3195 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3196 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003197 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003198 return true;
3199 }
3200 return false;
3201}
3202
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003203/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3204/// garbage collection attribute.
3205///
3206QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003207 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003208 if (getLangOptions().ObjC1 &&
3209 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003210 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003211 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003212 // (or pointers to them) be treated as though they were declared
3213 // as __strong.
3214 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003215 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003216 GCAttrs = QualType::Strong;
3217 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003218 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003219 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003220 // Non-pointers have none gc'able attribute regardless of the attribute
3221 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003222 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003223 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003224 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003225 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003226}
3227
Chris Lattner6ac46a42008-04-07 06:51:04 +00003228//===----------------------------------------------------------------------===//
3229// Type Compatibility Testing
3230//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003231
Chris Lattner6ac46a42008-04-07 06:51:04 +00003232/// areCompatVectorTypes - Return true if the two specified vector types are
3233/// compatible.
3234static bool areCompatVectorTypes(const VectorType *LHS,
3235 const VectorType *RHS) {
3236 assert(LHS->isCanonical() && RHS->isCanonical());
3237 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003238 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003239}
3240
Steve Naroff4084c302009-07-23 01:01:38 +00003241//===----------------------------------------------------------------------===//
3242// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3243//===----------------------------------------------------------------------===//
3244
3245/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3246/// inheritance hierarchy of 'rProto'.
3247static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3248 ObjCProtocolDecl *rProto) {
3249 if (lProto == rProto)
3250 return true;
3251 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3252 E = rProto->protocol_end(); PI != E; ++PI)
3253 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3254 return true;
3255 return false;
3256}
3257
3258/// ClassImplementsProtocol - Checks that 'lProto' protocol
3259/// has been implemented in IDecl class, its super class or categories (if
3260/// lookupCategory is true).
3261static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
3262 ObjCInterfaceDecl *IDecl,
3263 bool lookupCategory,
3264 bool RHSIsQualifiedID = false) {
3265
3266 // 1st, look up the class.
3267 const ObjCList<ObjCProtocolDecl> &Protocols =
3268 IDecl->getReferencedProtocols();
3269
3270 for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
3271 E = Protocols.end(); PI != E; ++PI) {
3272 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3273 return true;
3274 // This is dubious and is added to be compatible with gcc. In gcc, it is
3275 // also allowed assigning a protocol-qualified 'id' type to a LHS object
3276 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
3277 // object. This IMO, should be a bug.
3278 // FIXME: Treat this as an extension, and flag this as an error when GCC
3279 // extensions are not enabled.
3280 if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto))
3281 return true;
3282 }
3283
3284 // 2nd, look up the category.
3285 if (lookupCategory)
3286 for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
3287 CDecl = CDecl->getNextClassCategory()) {
3288 for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
3289 E = CDecl->protocol_end(); PI != E; ++PI)
3290 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3291 return true;
3292 }
3293
3294 // 3rd, look up the super class(s)
3295 if (IDecl->getSuperClass())
3296 return
3297 ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory,
3298 RHSIsQualifiedID);
3299
3300 return false;
3301}
3302
3303/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3304/// return true if lhs's protocols conform to rhs's protocol; false
3305/// otherwise.
3306bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3307 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3308 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3309 return false;
3310}
3311
3312/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3313/// ObjCQualifiedIDType.
3314bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3315 bool compare) {
3316 // Allow id<P..> and an 'id' or void* type in all cases.
3317 if (lhs->isVoidPointerType() ||
3318 lhs->isObjCIdType() || lhs->isObjCClassType())
3319 return true;
3320 else if (rhs->isVoidPointerType() ||
3321 rhs->isObjCIdType() || rhs->isObjCClassType())
3322 return true;
3323
3324 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3325 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3326
3327 if (!rhsOPT) return false;
3328
3329 if (rhsOPT->qual_empty()) {
3330 // If the RHS is a unqualified interface pointer "NSString*",
3331 // make sure we check the class hierarchy.
3332 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3333 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3334 E = lhsQID->qual_end(); I != E; ++I) {
3335 // when comparing an id<P> on lhs with a static type on rhs,
3336 // see if static class implements all of id's protocols, directly or
3337 // through its super class and categories.
3338 if (!ClassImplementsProtocol(*I, rhsID, true))
3339 return false;
3340 }
3341 }
3342 // If there are no qualifiers and no interface, we have an 'id'.
3343 return true;
3344 }
3345 // Both the right and left sides have qualifiers.
3346 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3347 E = lhsQID->qual_end(); I != E; ++I) {
3348 ObjCProtocolDecl *lhsProto = *I;
3349 bool match = false;
3350
3351 // when comparing an id<P> on lhs with a static type on rhs,
3352 // see if static class implements all of id's protocols, directly or
3353 // through its super class and categories.
3354 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3355 E = rhsOPT->qual_end(); J != E; ++J) {
3356 ObjCProtocolDecl *rhsProto = *J;
3357 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3358 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3359 match = true;
3360 break;
3361 }
3362 }
3363 // If the RHS is a qualified interface pointer "NSString<P>*",
3364 // make sure we check the class hierarchy.
3365 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3366 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3367 E = lhsQID->qual_end(); I != E; ++I) {
3368 // when comparing an id<P> on lhs with a static type on rhs,
3369 // see if static class implements all of id's protocols, directly or
3370 // through its super class and categories.
3371 if (ClassImplementsProtocol(*I, rhsID, true)) {
3372 match = true;
3373 break;
3374 }
3375 }
3376 }
3377 if (!match)
3378 return false;
3379 }
3380
3381 return true;
3382 }
3383
3384 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3385 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3386
3387 if (const ObjCObjectPointerType *lhsOPT =
3388 lhs->getAsObjCInterfacePointerType()) {
3389 if (lhsOPT->qual_empty()) {
3390 bool match = false;
3391 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3392 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3393 E = rhsQID->qual_end(); I != E; ++I) {
3394 // when comparing an id<P> on lhs with a static type on rhs,
3395 // see if static class implements all of id's protocols, directly or
3396 // through its super class and categories.
3397 if (ClassImplementsProtocol(*I, lhsID, true)) {
3398 match = true;
3399 break;
3400 }
3401 }
3402 if (!match)
3403 return false;
3404 }
3405 return true;
3406 }
3407 // Both the right and left sides have qualifiers.
3408 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3409 E = lhsOPT->qual_end(); I != E; ++I) {
3410 ObjCProtocolDecl *lhsProto = *I;
3411 bool match = false;
3412
3413 // when comparing an id<P> on lhs with a static type on rhs,
3414 // see if static class implements all of id's protocols, directly or
3415 // through its super class and categories.
3416 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3417 E = rhsQID->qual_end(); J != E; ++J) {
3418 ObjCProtocolDecl *rhsProto = *J;
3419 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3420 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3421 match = true;
3422 break;
3423 }
3424 }
3425 if (!match)
3426 return false;
3427 }
3428 return true;
3429 }
3430 return false;
3431}
3432
Eli Friedman3d815e72008-08-22 00:56:42 +00003433/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003434/// compatible for assignment from RHS to LHS. This handles validation of any
3435/// protocol qualifiers on the LHS or RHS.
3436///
Steve Naroff14108da2009-07-10 23:34:53 +00003437bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3438 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003439 // If either type represents the built-in 'id' or 'Class' types, return true.
3440 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003441 return true;
3442
Steve Naroff4084c302009-07-23 01:01:38 +00003443 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3444 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3445 QualType(RHSOPT,0),
3446 false);
3447
Steve Naroff14108da2009-07-10 23:34:53 +00003448 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3449 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003450 if (LHS && RHS) // We have 2 user-defined types.
3451 return canAssignObjCInterfaces(LHS, RHS);
3452
3453 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003454}
3455
Eli Friedman3d815e72008-08-22 00:56:42 +00003456bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3457 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003458 // Verify that the base decls are compatible: the RHS must be a subclass of
3459 // the LHS.
3460 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3461 return false;
3462
3463 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3464 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003465 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003466 return true;
3467
3468 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3469 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003470 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003471 return true; // FIXME: should return false!
3472
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003473 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3474 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003475 LHSPI != LHSPE; LHSPI++) {
3476 bool RHSImplementsProtocol = false;
3477
3478 // If the RHS doesn't implement the protocol on the left, the types
3479 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003480 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003481 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003482 RHSPI != RHSPE; RHSPI++) {
3483 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003484 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003485 break;
3486 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003487 }
3488 // FIXME: For better diagnostics, consider passing back the protocol name.
3489 if (!RHSImplementsProtocol)
3490 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003491 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003492 // The RHS implements all protocols listed on the LHS.
3493 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003494}
3495
Steve Naroff389bf462009-02-12 17:52:19 +00003496bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3497 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003498 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3499 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003500
Steve Naroff14108da2009-07-10 23:34:53 +00003501 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003502 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003503
3504 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3505 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003506}
3507
Steve Naroffec0550f2007-10-15 20:41:53 +00003508/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3509/// both shall have the identically qualified version of a compatible type.
3510/// C99 6.2.7p1: Two types have compatible types if their types are the
3511/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003512bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3513 return !mergeTypes(LHS, RHS).isNull();
3514}
3515
3516QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3517 const FunctionType *lbase = lhs->getAsFunctionType();
3518 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003519 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3520 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003521 bool allLTypes = true;
3522 bool allRTypes = true;
3523
3524 // Check return type
3525 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3526 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003527 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3528 allLTypes = false;
3529 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3530 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003531 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003532 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3533 if (NoReturn != lbase->getNoReturnAttr())
3534 allLTypes = false;
3535 if (NoReturn != rbase->getNoReturnAttr())
3536 allRTypes = false;
3537
Eli Friedman3d815e72008-08-22 00:56:42 +00003538 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003539 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3540 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003541 unsigned lproto_nargs = lproto->getNumArgs();
3542 unsigned rproto_nargs = rproto->getNumArgs();
3543
3544 // Compatible functions must have the same number of arguments
3545 if (lproto_nargs != rproto_nargs)
3546 return QualType();
3547
3548 // Variadic and non-variadic functions aren't compatible
3549 if (lproto->isVariadic() != rproto->isVariadic())
3550 return QualType();
3551
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003552 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3553 return QualType();
3554
Eli Friedman3d815e72008-08-22 00:56:42 +00003555 // Check argument compatibility
3556 llvm::SmallVector<QualType, 10> types;
3557 for (unsigned i = 0; i < lproto_nargs; i++) {
3558 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3559 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3560 QualType argtype = mergeTypes(largtype, rargtype);
3561 if (argtype.isNull()) return QualType();
3562 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003563 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3564 allLTypes = false;
3565 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3566 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003567 }
3568 if (allLTypes) return lhs;
3569 if (allRTypes) return rhs;
3570 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003571 lproto->isVariadic(), lproto->getTypeQuals(),
3572 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003573 }
3574
3575 if (lproto) allRTypes = false;
3576 if (rproto) allLTypes = false;
3577
Douglas Gregor72564e72009-02-26 23:50:07 +00003578 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003579 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003580 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003581 if (proto->isVariadic()) return QualType();
3582 // Check that the types are compatible with the types that
3583 // would result from default argument promotions (C99 6.7.5.3p15).
3584 // The only types actually affected are promotable integer
3585 // types and floats, which would be passed as a different
3586 // type depending on whether the prototype is visible.
3587 unsigned proto_nargs = proto->getNumArgs();
3588 for (unsigned i = 0; i < proto_nargs; ++i) {
3589 QualType argTy = proto->getArgType(i);
3590 if (argTy->isPromotableIntegerType() ||
3591 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3592 return QualType();
3593 }
3594
3595 if (allLTypes) return lhs;
3596 if (allRTypes) return rhs;
3597 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003598 proto->getNumArgs(), proto->isVariadic(),
3599 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003600 }
3601
3602 if (allLTypes) return lhs;
3603 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003604 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003605}
3606
3607QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003608 // C++ [expr]: If an expression initially has the type "reference to T", the
3609 // type is adjusted to "T" prior to any further analysis, the expression
3610 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003611 // expression is an lvalue unless the reference is an rvalue reference and
3612 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003613 // FIXME: C++ shouldn't be going through here! The rules are different
3614 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003615 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3616 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003617 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003618 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003619 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003620 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003621
Eli Friedman3d815e72008-08-22 00:56:42 +00003622 QualType LHSCan = getCanonicalType(LHS),
3623 RHSCan = getCanonicalType(RHS);
3624
3625 // If two types are identical, they are compatible.
3626 if (LHSCan == RHSCan)
3627 return LHS;
3628
3629 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003630 // Note that we handle extended qualifiers later, in the
3631 // case for ExtQualType.
3632 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003633 return QualType();
3634
Eli Friedman852d63b2009-06-01 01:22:52 +00003635 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3636 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003637
Chris Lattner1adb8832008-01-14 05:45:46 +00003638 // We want to consider the two function types to be the same for these
3639 // comparisons, just force one to the other.
3640 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3641 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003642
Eli Friedman07d25872009-06-02 05:28:56 +00003643 // Strip off objc_gc attributes off the top level so they can be merged.
3644 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003645 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003646 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3647 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003648 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003649 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003650 // __strong attribue is redundant if other decl is an objective-c
3651 // object pointer (or decorated with __strong attribute); otherwise
3652 // issue error.
3653 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3654 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003655 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003656 return QualType();
3657
Eli Friedman07d25872009-06-02 05:28:56 +00003658 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3659 RHS.getCVRQualifiers());
3660 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003661 if (!Result.isNull()) {
3662 if (Result.getObjCGCAttr() == QualType::GCNone)
3663 Result = getObjCGCQualType(Result, GCAttr);
3664 else if (Result.getObjCGCAttr() != GCAttr)
3665 Result = QualType();
3666 }
Eli Friedman07d25872009-06-02 05:28:56 +00003667 return Result;
3668 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003669 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003670 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003671 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3672 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003673 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3674 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003675 // __strong attribue is redundant if other decl is an objective-c
3676 // object pointer (or decorated with __strong attribute); otherwise
3677 // issue error.
3678 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3679 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003680 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003681 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003682
Eli Friedman07d25872009-06-02 05:28:56 +00003683 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3684 LHS.getCVRQualifiers());
3685 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003686 if (!Result.isNull()) {
3687 if (Result.getObjCGCAttr() == QualType::GCNone)
3688 Result = getObjCGCQualType(Result, GCAttr);
3689 else if (Result.getObjCGCAttr() != GCAttr)
3690 Result = QualType();
3691 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003692 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003693 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003694 }
3695
Eli Friedman4c721d32008-02-12 08:23:06 +00003696 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003697 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3698 LHSClass = Type::ConstantArray;
3699 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3700 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003701
Nate Begeman213541a2008-04-18 23:10:10 +00003702 // Canonicalize ExtVector -> Vector.
3703 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3704 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003705
3706 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003707 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003708 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3709 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003710 if (const EnumType* ETy = LHS->getAsEnumType()) {
3711 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3712 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003713 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003714 if (const EnumType* ETy = RHS->getAsEnumType()) {
3715 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3716 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003717 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003718
Eli Friedman3d815e72008-08-22 00:56:42 +00003719 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003720 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003721
Steve Naroff4a746782008-01-09 22:43:08 +00003722 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003723 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003724#define TYPE(Class, Base)
3725#define ABSTRACT_TYPE(Class, Base)
3726#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3727#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3728#include "clang/AST/TypeNodes.def"
3729 assert(false && "Non-canonical and dependent types shouldn't get here");
3730 return QualType();
3731
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003732 case Type::LValueReference:
3733 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003734 case Type::MemberPointer:
3735 assert(false && "C++ should never be in mergeTypes");
3736 return QualType();
3737
3738 case Type::IncompleteArray:
3739 case Type::VariableArray:
3740 case Type::FunctionProto:
3741 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003742 assert(false && "Types are eliminated above");
3743 return QualType();
3744
Chris Lattner1adb8832008-01-14 05:45:46 +00003745 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003746 {
3747 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003748 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
3749 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003750 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3751 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003752 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003753 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003754 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003755 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003756 return getPointerType(ResultType);
3757 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003758 case Type::BlockPointer:
3759 {
3760 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003761 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
3762 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003763 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3764 if (ResultType.isNull()) return QualType();
3765 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3766 return LHS;
3767 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3768 return RHS;
3769 return getBlockPointerType(ResultType);
3770 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003771 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003772 {
3773 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3774 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3775 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3776 return QualType();
3777
3778 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3779 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3780 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3781 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003782 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3783 return LHS;
3784 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3785 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003786 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3787 ArrayType::ArraySizeModifier(), 0);
3788 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3789 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003790 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3791 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003792 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3793 return LHS;
3794 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3795 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003796 if (LVAT) {
3797 // FIXME: This isn't correct! But tricky to implement because
3798 // the array's size has to be the size of LHS, but the type
3799 // has to be different.
3800 return LHS;
3801 }
3802 if (RVAT) {
3803 // FIXME: This isn't correct! But tricky to implement because
3804 // the array's size has to be the size of RHS, but the type
3805 // has to be different.
3806 return RHS;
3807 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003808 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3809 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003810 return getIncompleteArrayType(ResultType,
3811 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003812 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003813 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003814 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003815 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003816 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003817 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003818 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003819 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003820 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003821 case Type::Complex:
3822 // Distinct complex types are incompatible.
3823 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003824 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003825 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003826 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3827 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003828 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003829 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003830 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003831 // FIXME: This should be type compatibility, e.g. whether
3832 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003833 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3834 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3835 if (LHSIface && RHSIface &&
3836 canAssignObjCInterfaces(LHSIface, RHSIface))
3837 return LHS;
3838
Eli Friedman3d815e72008-08-22 00:56:42 +00003839 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003840 }
Steve Naroff14108da2009-07-10 23:34:53 +00003841 case Type::ObjCObjectPointer: {
Steve Naroff14108da2009-07-10 23:34:53 +00003842 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3843 RHS->getAsObjCObjectPointerType()))
3844 return LHS;
3845
Steve Naroffbc76dd02008-12-10 22:14:21 +00003846 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003847 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003848 case Type::FixedWidthInt:
3849 // Distinct fixed-width integers are not compatible.
3850 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003851 case Type::ExtQual:
3852 // FIXME: ExtQual types can be compatible even if they're not
3853 // identical!
3854 return QualType();
3855 // First attempt at an implementation, but I'm not really sure it's
3856 // right...
3857#if 0
3858 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3859 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3860 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3861 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3862 return QualType();
3863 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3864 LHSBase = QualType(LQual->getBaseType(), 0);
3865 RHSBase = QualType(RQual->getBaseType(), 0);
3866 ResultType = mergeTypes(LHSBase, RHSBase);
3867 if (ResultType.isNull()) return QualType();
3868 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3869 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3870 return LHS;
3871 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3872 return RHS;
3873 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3874 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3875 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3876 return ResultType;
3877#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003878
3879 case Type::TemplateSpecialization:
3880 assert(false && "Dependent types have no size");
3881 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003882 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003883
3884 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003885}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003886
Chris Lattner5426bf62008-04-07 07:01:58 +00003887//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003888// Integer Predicates
3889//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003890
Eli Friedmanad74a752008-06-28 06:23:08 +00003891unsigned ASTContext::getIntWidth(QualType T) {
3892 if (T == BoolTy)
3893 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003894 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3895 return FWIT->getWidth();
3896 }
3897 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003898 return (unsigned)getTypeSize(T);
3899}
3900
3901QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3902 assert(T->isSignedIntegerType() && "Unexpected type");
3903 if (const EnumType* ETy = T->getAsEnumType())
3904 T = ETy->getDecl()->getIntegerType();
3905 const BuiltinType* BTy = T->getAsBuiltinType();
3906 assert (BTy && "Unexpected signed integer type");
3907 switch (BTy->getKind()) {
3908 case BuiltinType::Char_S:
3909 case BuiltinType::SChar:
3910 return UnsignedCharTy;
3911 case BuiltinType::Short:
3912 return UnsignedShortTy;
3913 case BuiltinType::Int:
3914 return UnsignedIntTy;
3915 case BuiltinType::Long:
3916 return UnsignedLongTy;
3917 case BuiltinType::LongLong:
3918 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003919 case BuiltinType::Int128:
3920 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003921 default:
3922 assert(0 && "Unexpected signed integer type");
3923 return QualType();
3924 }
3925}
3926
Douglas Gregor2cf26342009-04-09 22:27:44 +00003927ExternalASTSource::~ExternalASTSource() { }
3928
3929void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003930
3931
3932//===----------------------------------------------------------------------===//
3933// Builtin Type Computation
3934//===----------------------------------------------------------------------===//
3935
3936/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3937/// pointer over the consumed characters. This returns the resultant type.
3938static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3939 ASTContext::GetBuiltinTypeError &Error,
3940 bool AllowTypeModifiers = true) {
3941 // Modifiers.
3942 int HowLong = 0;
3943 bool Signed = false, Unsigned = false;
3944
3945 // Read the modifiers first.
3946 bool Done = false;
3947 while (!Done) {
3948 switch (*Str++) {
3949 default: Done = true; --Str; break;
3950 case 'S':
3951 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3952 assert(!Signed && "Can't use 'S' modifier multiple times!");
3953 Signed = true;
3954 break;
3955 case 'U':
3956 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3957 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3958 Unsigned = true;
3959 break;
3960 case 'L':
3961 assert(HowLong <= 2 && "Can't have LLLL modifier");
3962 ++HowLong;
3963 break;
3964 }
3965 }
3966
3967 QualType Type;
3968
3969 // Read the base type.
3970 switch (*Str++) {
3971 default: assert(0 && "Unknown builtin type letter!");
3972 case 'v':
3973 assert(HowLong == 0 && !Signed && !Unsigned &&
3974 "Bad modifiers used with 'v'!");
3975 Type = Context.VoidTy;
3976 break;
3977 case 'f':
3978 assert(HowLong == 0 && !Signed && !Unsigned &&
3979 "Bad modifiers used with 'f'!");
3980 Type = Context.FloatTy;
3981 break;
3982 case 'd':
3983 assert(HowLong < 2 && !Signed && !Unsigned &&
3984 "Bad modifiers used with 'd'!");
3985 if (HowLong)
3986 Type = Context.LongDoubleTy;
3987 else
3988 Type = Context.DoubleTy;
3989 break;
3990 case 's':
3991 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3992 if (Unsigned)
3993 Type = Context.UnsignedShortTy;
3994 else
3995 Type = Context.ShortTy;
3996 break;
3997 case 'i':
3998 if (HowLong == 3)
3999 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4000 else if (HowLong == 2)
4001 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4002 else if (HowLong == 1)
4003 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4004 else
4005 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4006 break;
4007 case 'c':
4008 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4009 if (Signed)
4010 Type = Context.SignedCharTy;
4011 else if (Unsigned)
4012 Type = Context.UnsignedCharTy;
4013 else
4014 Type = Context.CharTy;
4015 break;
4016 case 'b': // boolean
4017 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4018 Type = Context.BoolTy;
4019 break;
4020 case 'z': // size_t.
4021 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4022 Type = Context.getSizeType();
4023 break;
4024 case 'F':
4025 Type = Context.getCFConstantStringType();
4026 break;
4027 case 'a':
4028 Type = Context.getBuiltinVaListType();
4029 assert(!Type.isNull() && "builtin va list type not initialized!");
4030 break;
4031 case 'A':
4032 // This is a "reference" to a va_list; however, what exactly
4033 // this means depends on how va_list is defined. There are two
4034 // different kinds of va_list: ones passed by value, and ones
4035 // passed by reference. An example of a by-value va_list is
4036 // x86, where va_list is a char*. An example of by-ref va_list
4037 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4038 // we want this argument to be a char*&; for x86-64, we want
4039 // it to be a __va_list_tag*.
4040 Type = Context.getBuiltinVaListType();
4041 assert(!Type.isNull() && "builtin va list type not initialized!");
4042 if (Type->isArrayType()) {
4043 Type = Context.getArrayDecayedType(Type);
4044 } else {
4045 Type = Context.getLValueReferenceType(Type);
4046 }
4047 break;
4048 case 'V': {
4049 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004050 unsigned NumElements = strtoul(Str, &End, 10);
4051 assert(End != Str && "Missing vector size");
4052
4053 Str = End;
4054
4055 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4056 Type = Context.getVectorType(ElementType, NumElements);
4057 break;
4058 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004059 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004060 Type = Context.getFILEType();
4061 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004062 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004063 return QualType();
4064 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004065 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004066 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004067 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004068 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004069 else
4070 Type = Context.getjmp_bufType();
4071
Mike Stumpfd612db2009-07-28 23:47:15 +00004072 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004073 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004074 return QualType();
4075 }
4076 break;
Mike Stump782fa302009-07-28 02:25:19 +00004077 }
Chris Lattner86df27b2009-06-14 00:45:47 +00004078
4079 if (!AllowTypeModifiers)
4080 return Type;
4081
4082 Done = false;
4083 while (!Done) {
4084 switch (*Str++) {
4085 default: Done = true; --Str; break;
4086 case '*':
4087 Type = Context.getPointerType(Type);
4088 break;
4089 case '&':
4090 Type = Context.getLValueReferenceType(Type);
4091 break;
4092 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4093 case 'C':
4094 Type = Type.getQualifiedType(QualType::Const);
4095 break;
4096 }
4097 }
4098
4099 return Type;
4100}
4101
4102/// GetBuiltinType - Return the type for the specified builtin.
4103QualType ASTContext::GetBuiltinType(unsigned id,
4104 GetBuiltinTypeError &Error) {
4105 const char *TypeStr = BuiltinInfo.GetTypeString(id);
4106
4107 llvm::SmallVector<QualType, 8> ArgTypes;
4108
4109 Error = GE_None;
4110 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4111 if (Error != GE_None)
4112 return QualType();
4113 while (TypeStr[0] && TypeStr[0] != '.') {
4114 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4115 if (Error != GE_None)
4116 return QualType();
4117
4118 // Do array -> pointer decay. The builtin should use the decayed type.
4119 if (Ty->isArrayType())
4120 Ty = getArrayDecayedType(Ty);
4121
4122 ArgTypes.push_back(Ty);
4123 }
4124
4125 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4126 "'.' should only occur at end of builtin type list!");
4127
4128 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4129 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4130 return getFunctionNoProtoType(ResType);
4131 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4132 TypeStr[0] == '.', 0);
4133}