blob: 680ec24eff601e6e2505f07753b56d915403f245 [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),
Douglas Gregorc29f77b2009-07-07 16:35:42 +000041 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
42 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 Gregor2e222532009-07-02 17:08:52 +0000223namespace {
224 class BeforeInTranslationUnit
225 : std::binary_function<SourceRange, SourceRange, bool> {
226 SourceManager *SourceMgr;
227
228 public:
229 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
230
231 bool operator()(SourceRange X, SourceRange Y) {
232 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
233 }
234 };
235}
236
237/// \brief Determine whether the given comment is a Doxygen-style comment.
238///
239/// \param Start the start of the comment text.
240///
241/// \param End the end of the comment text.
242///
243/// \param Member whether we want to check whether this is a member comment
244/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
245/// we only return true when we find a non-member comment.
246static bool
247isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
248 bool Member = false) {
249 const char *BufferStart
250 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
251 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
252 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
253
254 if (End - Start < 4)
255 return false;
256
257 assert(Start[0] == '/' && "Not a comment?");
258 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
259 return false;
260 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
261 return false;
262
263 return (Start[3] == '<') == Member;
264}
265
266/// \brief Retrieve the comment associated with the given declaration, if
267/// it has one.
268const char *ASTContext::getCommentForDecl(const Decl *D) {
269 if (!D)
270 return 0;
271
272 // Check whether we have cached a comment string for this declaration
273 // already.
274 llvm::DenseMap<const Decl *, std::string>::iterator Pos
275 = DeclComments.find(D);
276 if (Pos != DeclComments.end())
277 return Pos->second.c_str();
278
279 // If we have an external AST source and have not yet loaded comments from
280 // that source, do so now.
281 if (ExternalSource && !LoadedExternalComments) {
282 std::vector<SourceRange> LoadedComments;
283 ExternalSource->ReadComments(LoadedComments);
284
285 if (!LoadedComments.empty())
286 Comments.insert(Comments.begin(), LoadedComments.begin(),
287 LoadedComments.end());
288
289 LoadedExternalComments = true;
290 }
291
292 // If there are no comments anywhere, we won't find anything.
293 if (Comments.empty())
294 return 0;
295
296 // If the declaration doesn't map directly to a location in a file, we
297 // can't find the comment.
298 SourceLocation DeclStartLoc = D->getLocStart();
299 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
300 return 0;
301
302 // Find the comment that occurs just before this declaration.
303 std::vector<SourceRange>::iterator LastComment
304 = std::lower_bound(Comments.begin(), Comments.end(),
305 SourceRange(DeclStartLoc),
306 BeforeInTranslationUnit(&SourceMgr));
307
308 // Decompose the location for the start of the declaration and find the
309 // beginning of the file buffer.
310 std::pair<FileID, unsigned> DeclStartDecomp
311 = SourceMgr.getDecomposedLoc(DeclStartLoc);
312 const char *FileBufferStart
313 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
314
315 // First check whether we have a comment for a member.
316 if (LastComment != Comments.end() &&
317 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
318 isDoxygenComment(SourceMgr, *LastComment, true)) {
319 std::pair<FileID, unsigned> LastCommentEndDecomp
320 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
321 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
322 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
323 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
324 LastCommentEndDecomp.second)) {
325 // The Doxygen member comment comes after the declaration starts and
326 // is on the same line and in the same file as the declaration. This
327 // is the comment we want.
328 std::string &Result = DeclComments[D];
329 Result.append(FileBufferStart +
330 SourceMgr.getFileOffset(LastComment->getBegin()),
331 FileBufferStart + LastCommentEndDecomp.second + 1);
332 return Result.c_str();
333 }
334 }
335
336 if (LastComment == Comments.begin())
337 return 0;
338 --LastComment;
339
340 // Decompose the end of the comment.
341 std::pair<FileID, unsigned> LastCommentEndDecomp
342 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
343
344 // If the comment and the declaration aren't in the same file, then they
345 // aren't related.
346 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
347 return 0;
348
349 // Check that we actually have a Doxygen comment.
350 if (!isDoxygenComment(SourceMgr, *LastComment))
351 return 0;
352
353 // Compute the starting line for the declaration and for the end of the
354 // comment (this is expensive).
355 unsigned DeclStartLine
356 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
357 unsigned CommentEndLine
358 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
359 LastCommentEndDecomp.second);
360
361 // If the comment does not end on the line prior to the declaration, then
362 // the comment is not associated with the declaration at all.
363 if (CommentEndLine + 1 != DeclStartLine)
364 return 0;
365
366 // We have a comment, but there may be more comments on the previous lines.
367 // Keep looking so long as the comments are still Doxygen comments and are
368 // still adjacent.
369 unsigned ExpectedLine
370 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
371 std::vector<SourceRange>::iterator FirstComment = LastComment;
372 while (FirstComment != Comments.begin()) {
373 // Look at the previous comment
374 --FirstComment;
375 std::pair<FileID, unsigned> Decomp
376 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
377
378 // If this previous comment is in a different file, we're done.
379 if (Decomp.first != DeclStartDecomp.first) {
380 ++FirstComment;
381 break;
382 }
383
384 // If this comment is not a Doxygen comment, we're done.
385 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
386 ++FirstComment;
387 break;
388 }
389
390 // If the line number is not what we expected, we're done.
391 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
392 if (Line != ExpectedLine) {
393 ++FirstComment;
394 break;
395 }
396
397 // Set the next expected line number.
398 ExpectedLine
399 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
400 }
401
402 // The iterator range [FirstComment, LastComment] contains all of the
403 // BCPL comments that, together, are associated with this declaration.
404 // Form a single comment block string for this declaration that concatenates
405 // all of these comments.
406 std::string &Result = DeclComments[D];
407 while (FirstComment != LastComment) {
408 std::pair<FileID, unsigned> DecompStart
409 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
410 std::pair<FileID, unsigned> DecompEnd
411 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
412 Result.append(FileBufferStart + DecompStart.second,
413 FileBufferStart + DecompEnd.second + 1);
414 ++FirstComment;
415 }
416
417 // Append the last comment line.
418 Result.append(FileBufferStart +
419 SourceMgr.getFileOffset(LastComment->getBegin()),
420 FileBufferStart + LastCommentEndDecomp.second + 1);
421 return Result.c_str();
422}
423
Chris Lattner464175b2007-07-18 17:52:12 +0000424//===----------------------------------------------------------------------===//
425// Type Sizing and Analysis
426//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000427
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000428/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
429/// scalar floating point type.
430const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
431 const BuiltinType *BT = T->getAsBuiltinType();
432 assert(BT && "Not a floating point type!");
433 switch (BT->getKind()) {
434 default: assert(0 && "Not a floating point type!");
435 case BuiltinType::Float: return Target.getFloatFormat();
436 case BuiltinType::Double: return Target.getDoubleFormat();
437 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
438 }
439}
440
Chris Lattneraf707ab2009-01-24 21:53:27 +0000441/// getDeclAlign - Return a conservative estimate of the alignment of the
442/// specified decl. Note that bitfields do not have a valid alignment, so
443/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000444unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000445 unsigned Align = Target.getCharWidth();
446
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000447 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000448 Align = std::max(Align, AA->getAlignment());
449
Chris Lattneraf707ab2009-01-24 21:53:27 +0000450 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
451 QualType T = VD->getType();
Ted Kremenek35366a62009-07-17 17:50:17 +0000452 if (const ReferenceType* RT = T->getAsReferenceType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000453 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000454 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000455 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
456 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000457 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
458 T = cast<ArrayType>(T)->getElementType();
459
460 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
461 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000462 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000463
464 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000465}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000466
Chris Lattnera7674d82007-07-13 22:13:22 +0000467/// getTypeSize - Return the size of the specified type, in bits. This method
468/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000469std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000470ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000471 uint64_t Width=0;
472 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000473 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000474#define TYPE(Class, Base)
475#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000476#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000477#define DEPENDENT_TYPE(Class, Base) case Type::Class:
478#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000479 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000480 break;
481
Chris Lattner692233e2007-07-13 22:27:08 +0000482 case Type::FunctionNoProto:
483 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000484 // GCC extension: alignof(function) = 32 bits
485 Width = 0;
486 Align = 32;
487 break;
488
Douglas Gregor72564e72009-02-26 23:50:07 +0000489 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000490 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000491 Width = 0;
492 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
493 break;
494
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000495 case Type::ConstantArrayWithExpr:
496 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000497 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000498 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000499
Chris Lattner98be4942008-03-05 18:54:05 +0000500 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000501 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000502 Align = EltInfo.second;
503 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000504 }
Nate Begeman213541a2008-04-18 23:10:10 +0000505 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000506 case Type::Vector: {
507 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000508 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000509 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000510 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000511 // If the alignment is not a power of 2, round up to the next power of 2.
512 // This happens for non-power-of-2 length vectors.
513 // FIXME: this should probably be a target property.
514 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000515 break;
516 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000517
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000518 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000519 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000520 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000521 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000522 // GCC extension: alignof(void) = 8 bits.
523 Width = 0;
524 Align = 8;
525 break;
526
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000527 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000528 Width = Target.getBoolWidth();
529 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000530 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000531 case BuiltinType::Char_S:
532 case BuiltinType::Char_U:
533 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000534 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000535 Width = Target.getCharWidth();
536 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000537 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000538 case BuiltinType::WChar:
539 Width = Target.getWCharWidth();
540 Align = Target.getWCharAlign();
541 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000542 case BuiltinType::Char16:
543 Width = Target.getChar16Width();
544 Align = Target.getChar16Align();
545 break;
546 case BuiltinType::Char32:
547 Width = Target.getChar32Width();
548 Align = Target.getChar32Align();
549 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000550 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000551 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000552 Width = Target.getShortWidth();
553 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000555 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000556 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000557 Width = Target.getIntWidth();
558 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000560 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000561 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000562 Width = Target.getLongWidth();
563 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000564 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000565 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000566 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000567 Width = Target.getLongLongWidth();
568 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000569 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000570 case BuiltinType::Int128:
571 case BuiltinType::UInt128:
572 Width = 128;
573 Align = 128; // int128_t is 128-bit aligned on all targets.
574 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000575 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000576 Width = Target.getFloatWidth();
577 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000578 break;
579 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000580 Width = Target.getDoubleWidth();
581 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000582 break;
583 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000584 Width = Target.getLongDoubleWidth();
585 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000586 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000587 case BuiltinType::NullPtr:
588 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
589 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000590 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000591 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000592 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000593 case Type::FixedWidthInt:
594 // FIXME: This isn't precisely correct; the width/alignment should depend
595 // on the available types for the target
596 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000597 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000598 Align = Width;
599 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000600 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000601 // FIXME: Pointers into different addr spaces could have different sizes and
602 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000603 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000604 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000605 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000606 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000607 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000608 case Type::BlockPointer: {
609 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
610 Width = Target.getPointerWidth(AS);
611 Align = Target.getPointerAlign(AS);
612 break;
613 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000614 case Type::Pointer: {
615 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000616 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000617 Align = Target.getPointerAlign(AS);
618 break;
619 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000620 case Type::LValueReference:
621 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000622 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000623 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000624 // FIXME: This is wrong for struct layout: a reference in a struct has
625 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000626 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000627 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000628 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
629 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
630 // If we ever want to support other ABIs this needs to be abstracted.
631
Sebastian Redlf30208a2009-01-24 21:16:55 +0000632 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000633 std::pair<uint64_t, unsigned> PtrDiffInfo =
634 getTypeInfo(getPointerDiffType());
635 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000636 if (Pointee->isFunctionType())
637 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000638 Align = PtrDiffInfo.second;
639 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000640 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000641 case Type::Complex: {
642 // Complex types have the same alignment as their elements, but twice the
643 // size.
644 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000645 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000646 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000647 Align = EltInfo.second;
648 break;
649 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000650 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000651 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000652 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
653 Width = Layout.getSize();
654 Align = Layout.getAlignment();
655 break;
656 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000657 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000658 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000659 const TagType *TT = cast<TagType>(T);
660
661 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000662 Width = 1;
663 Align = 1;
664 break;
665 }
666
Daniel Dunbar1d751182008-11-08 05:48:37 +0000667 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000668 return getTypeInfo(ET->getDecl()->getIntegerType());
669
Daniel Dunbar1d751182008-11-08 05:48:37 +0000670 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000671 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
672 Width = Layout.getSize();
673 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000674 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000675 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000676
Douglas Gregor18857642009-04-30 17:32:17 +0000677 case Type::Typedef: {
678 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000679 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000680 Align = Aligned->getAlignment();
681 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
682 } else
683 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000684 break;
Chris Lattner71763312008-04-06 22:05:18 +0000685 }
Douglas Gregor18857642009-04-30 17:32:17 +0000686
687 case Type::TypeOfExpr:
688 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
689 .getTypePtr());
690
691 case Type::TypeOf:
692 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
693
Anders Carlsson395b4752009-06-24 19:06:50 +0000694 case Type::Decltype:
695 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
696 .getTypePtr());
697
Douglas Gregor18857642009-04-30 17:32:17 +0000698 case Type::QualifiedName:
699 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
700
701 case Type::TemplateSpecialization:
702 assert(getCanonicalType(T) != T &&
703 "Cannot request the size of a dependent type");
704 // FIXME: this is likely to be wrong once we support template
705 // aliases, since a template alias could refer to a typedef that
706 // has an __aligned__ attribute on it.
707 return getTypeInfo(getCanonicalType(T));
708 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000709
Chris Lattner464175b2007-07-18 17:52:12 +0000710 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000711 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000712}
713
Chris Lattner34ebde42009-01-27 18:08:34 +0000714/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
715/// type for the current target in bits. This can be different than the ABI
716/// alignment in cases where it is beneficial for performance to overalign
717/// a data type.
718unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
719 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000720
721 // Double and long long should be naturally aligned if possible.
722 if (const ComplexType* CT = T->getAsComplexType())
723 T = CT->getElementType().getTypePtr();
724 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
725 T->isSpecificBuiltinType(BuiltinType::LongLong))
726 return std::max(ABIAlign, (unsigned)getTypeSize(T));
727
Chris Lattner34ebde42009-01-27 18:08:34 +0000728 return ABIAlign;
729}
730
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000731static void CollectLocalObjCIvars(ASTContext *Ctx,
732 const ObjCInterfaceDecl *OI,
733 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000734 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
735 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000736 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000737 if (!IVDecl->isInvalidDecl())
738 Fields.push_back(cast<FieldDecl>(IVDecl));
739 }
740}
741
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000742void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
743 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
744 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
745 CollectObjCIvars(SuperClass, Fields);
746 CollectLocalObjCIvars(this, OI, Fields);
747}
748
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000749/// ShallowCollectObjCIvars -
750/// Collect all ivars, including those synthesized, in the current class.
751///
752void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
753 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
754 bool CollectSynthesized) {
755 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
756 E = OI->ivar_end(); I != E; ++I) {
757 Ivars.push_back(*I);
758 }
759 if (CollectSynthesized)
760 CollectSynthesizedIvars(OI, Ivars);
761}
762
Fariborz Jahanian98200742009-05-12 18:14:29 +0000763void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
764 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000765 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
766 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000767 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
768 Ivars.push_back(Ivar);
769
770 // Also look into nested protocols.
771 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
772 E = PD->protocol_end(); P != E; ++P)
773 CollectProtocolSynthesizedIvars(*P, Ivars);
774}
775
776/// CollectSynthesizedIvars -
777/// This routine collect synthesized ivars for the designated class.
778///
779void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
780 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000781 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
782 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000783 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
784 Ivars.push_back(Ivar);
785 }
786 // Also look into interface's protocol list for properties declared
787 // in the protocol and whose ivars are synthesized.
788 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
789 PE = OI->protocol_end(); P != PE; ++P) {
790 ObjCProtocolDecl *PD = (*P);
791 CollectProtocolSynthesizedIvars(PD, Ivars);
792 }
793}
794
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000795unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
796 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000797 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
798 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000799 if ((*I)->getPropertyIvarDecl())
800 ++count;
801
802 // Also look into nested protocols.
803 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
804 E = PD->protocol_end(); P != E; ++P)
805 count += CountProtocolSynthesizedIvars(*P);
806 return count;
807}
808
809unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
810{
811 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000812 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
813 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000814 if ((*I)->getPropertyIvarDecl())
815 ++count;
816 }
817 // Also look into interface's protocol list for properties declared
818 // in the protocol and whose ivars are synthesized.
819 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
820 PE = OI->protocol_end(); P != PE; ++P) {
821 ObjCProtocolDecl *PD = (*P);
822 count += CountProtocolSynthesizedIvars(PD);
823 }
824 return count;
825}
826
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000827/// getInterfaceLayoutImpl - Get or compute information about the
828/// layout of the given interface.
829///
830/// \param Impl - If given, also include the layout of the interface's
831/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000832const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000833ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
834 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000835 assert(!D->isForwardDecl() && "Invalid interface decl!");
836
Devang Patel44a3dde2008-06-04 21:54:36 +0000837 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000838 ObjCContainerDecl *Key =
839 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
840 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
841 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000842
Daniel Dunbar453addb2009-05-03 11:16:44 +0000843 // Add in synthesized ivar count if laying out an implementation.
844 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000845 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000846 unsigned SynthCount = CountSynthesizedIvars(D);
847 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000848 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000849 // entry. Note we can't cache this because we simply free all
850 // entries later; however we shouldn't look up implementations
851 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000852 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000853 return getObjCLayout(D, 0);
854 }
855
Anders Carlsson29445a02009-07-18 21:19:52 +0000856 const ASTRecordLayout *NewEntry =
857 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
858 ObjCLayouts[Key] = NewEntry;
859
Devang Patel44a3dde2008-06-04 21:54:36 +0000860 return *NewEntry;
861}
862
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000863const ASTRecordLayout &
864ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
865 return getObjCLayout(D, 0);
866}
867
868const ASTRecordLayout &
869ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
870 return getObjCLayout(D->getClassInterface(), D);
871}
872
Devang Patel88a981b2007-11-01 19:11:01 +0000873/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000874/// specified record (struct/union/class), which indicates its size and field
875/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000876const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000877 D = D->getDefinition(*this);
878 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000879
Chris Lattner464175b2007-07-18 17:52:12 +0000880 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000881 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000882 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000883
Anders Carlsson29445a02009-07-18 21:19:52 +0000884 const ASTRecordLayout *NewEntry =
885 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Chris Lattner464175b2007-07-18 17:52:12 +0000886 Entry = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000887
Chris Lattner5d2a6302007-07-18 18:26:58 +0000888 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000889}
890
Chris Lattnera7674d82007-07-13 22:13:22 +0000891//===----------------------------------------------------------------------===//
892// Type creation/memoization methods
893//===----------------------------------------------------------------------===//
894
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000895QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000896 QualType CanT = getCanonicalType(T);
897 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000898 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000899
900 // If we are composing extended qualifiers together, merge together into one
901 // ExtQualType node.
902 unsigned CVRQuals = T.getCVRQualifiers();
903 QualType::GCAttrTypes GCAttr = QualType::GCNone;
904 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000905
Chris Lattnerb7d25532009-02-18 22:53:11 +0000906 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
907 // If this type already has an address space specified, it cannot get
908 // another one.
909 assert(EQT->getAddressSpace() == 0 &&
910 "Type cannot be in multiple addr spaces!");
911 GCAttr = EQT->getObjCGCAttr();
912 TypeNode = EQT->getBaseType();
913 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000914
Chris Lattnerb7d25532009-02-18 22:53:11 +0000915 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000916 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000917 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000918 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000919 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000920 return QualType(EXTQy, CVRQuals);
921
Christopher Lambebb97e92008-02-04 02:31:56 +0000922 // If the base type isn't canonical, this won't be a canonical type either,
923 // so fill in the canonical type field.
924 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000925 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000926 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000927
Chris Lattnerb7d25532009-02-18 22:53:11 +0000928 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000929 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000930 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000931 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000932 ExtQualType *New =
933 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000934 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000935 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000936 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000937}
938
Chris Lattnerb7d25532009-02-18 22:53:11 +0000939QualType ASTContext::getObjCGCQualType(QualType T,
940 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000941 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000942 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000943 return T;
944
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000945 if (T->isPointerType()) {
Ted Kremenek35366a62009-07-17 17:50:17 +0000946 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000947 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000948 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
949 return getPointerType(ResultType);
950 }
951 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000952 // If we are composing extended qualifiers together, merge together into one
953 // ExtQualType node.
954 unsigned CVRQuals = T.getCVRQualifiers();
955 Type *TypeNode = T.getTypePtr();
956 unsigned AddressSpace = 0;
957
958 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
959 // If this type already has an address space specified, it cannot get
960 // another one.
961 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
962 "Type cannot be in multiple addr spaces!");
963 AddressSpace = EQT->getAddressSpace();
964 TypeNode = EQT->getBaseType();
965 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000966
967 // Check if we've already instantiated an gc qual'd type of this type.
968 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000969 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000970 void *InsertPos = 0;
971 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000972 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000973
974 // If the base type isn't canonical, this won't be a canonical type either,
975 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000976 // FIXME: Isn't this also not canonical if the base type is a array
977 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000978 QualType Canonical;
979 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000980 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000981
Chris Lattnerb7d25532009-02-18 22:53:11 +0000982 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000983 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
984 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
985 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000986 ExtQualType *New =
987 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000988 ExtQualTypes.InsertNode(New, InsertPos);
989 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000990 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000991}
Chris Lattnera7674d82007-07-13 22:13:22 +0000992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993/// getComplexType - Return the uniqued reference to the type for a complex
994/// number with the specified element type.
995QualType ASTContext::getComplexType(QualType T) {
996 // Unique pointers, to guarantee there is only one pointer of a particular
997 // structure.
998 llvm::FoldingSetNodeID ID;
999 ComplexType::Profile(ID, T);
1000
1001 void *InsertPos = 0;
1002 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1003 return QualType(CT, 0);
1004
1005 // If the pointee type isn't canonical, this won't be a canonical type either,
1006 // so fill in the canonical type field.
1007 QualType Canonical;
1008 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001009 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001010
1011 // Get the new insert position for the node we care about.
1012 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001013 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 }
Steve Narofff83820b2009-01-27 22:08:43 +00001015 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 Types.push_back(New);
1017 ComplexTypes.InsertNode(New, InsertPos);
1018 return QualType(New, 0);
1019}
1020
Eli Friedmanf98aba32009-02-13 02:31:07 +00001021QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1022 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1023 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1024 FixedWidthIntType *&Entry = Map[Width];
1025 if (!Entry)
1026 Entry = new FixedWidthIntType(Width, Signed);
1027 return QualType(Entry, 0);
1028}
Reid Spencer5f016e22007-07-11 17:01:13 +00001029
1030/// getPointerType - Return the uniqued reference to the type for a pointer to
1031/// the specified type.
1032QualType ASTContext::getPointerType(QualType T) {
1033 // Unique pointers, to guarantee there is only one pointer of a particular
1034 // structure.
1035 llvm::FoldingSetNodeID ID;
1036 PointerType::Profile(ID, T);
1037
1038 void *InsertPos = 0;
1039 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1040 return QualType(PT, 0);
1041
1042 // If the pointee type isn't canonical, this won't be a canonical type either,
1043 // so fill in the canonical type field.
1044 QualType Canonical;
1045 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001046 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001047
1048 // Get the new insert position for the node we care about.
1049 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001050 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 }
Steve Narofff83820b2009-01-27 22:08:43 +00001052 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 Types.push_back(New);
1054 PointerTypes.InsertNode(New, InsertPos);
1055 return QualType(New, 0);
1056}
1057
Steve Naroff5618bd42008-08-27 16:04:49 +00001058/// getBlockPointerType - Return the uniqued reference to the type for
1059/// a pointer to the specified block.
1060QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001061 assert(T->isFunctionType() && "block of function types only");
1062 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001063 // structure.
1064 llvm::FoldingSetNodeID ID;
1065 BlockPointerType::Profile(ID, T);
1066
1067 void *InsertPos = 0;
1068 if (BlockPointerType *PT =
1069 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1070 return QualType(PT, 0);
1071
Steve Naroff296e8d52008-08-28 19:20:44 +00001072 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001073 // type either so fill in the canonical type field.
1074 QualType Canonical;
1075 if (!T->isCanonical()) {
1076 Canonical = getBlockPointerType(getCanonicalType(T));
1077
1078 // Get the new insert position for the node we care about.
1079 BlockPointerType *NewIP =
1080 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001081 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001082 }
Steve Narofff83820b2009-01-27 22:08:43 +00001083 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001084 Types.push_back(New);
1085 BlockPointerTypes.InsertNode(New, InsertPos);
1086 return QualType(New, 0);
1087}
1088
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001089/// getLValueReferenceType - Return the uniqued reference to the type for an
1090/// lvalue reference to the specified type.
1091QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 // Unique pointers, to guarantee there is only one pointer of a particular
1093 // structure.
1094 llvm::FoldingSetNodeID ID;
1095 ReferenceType::Profile(ID, T);
1096
1097 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001098 if (LValueReferenceType *RT =
1099 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 // If the referencee type isn't canonical, this won't be a canonical type
1103 // either, so fill in the canonical type field.
1104 QualType Canonical;
1105 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001106 Canonical = getLValueReferenceType(getCanonicalType(T));
1107
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001109 LValueReferenceType *NewIP =
1110 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001111 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 }
1113
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001114 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001116 LValueReferenceTypes.InsertNode(New, InsertPos);
1117 return QualType(New, 0);
1118}
1119
1120/// getRValueReferenceType - Return the uniqued reference to the type for an
1121/// rvalue reference to the specified type.
1122QualType ASTContext::getRValueReferenceType(QualType T) {
1123 // Unique pointers, to guarantee there is only one pointer of a particular
1124 // structure.
1125 llvm::FoldingSetNodeID ID;
1126 ReferenceType::Profile(ID, T);
1127
1128 void *InsertPos = 0;
1129 if (RValueReferenceType *RT =
1130 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1131 return QualType(RT, 0);
1132
1133 // If the referencee type isn't canonical, this won't be a canonical type
1134 // either, so fill in the canonical type field.
1135 QualType Canonical;
1136 if (!T->isCanonical()) {
1137 Canonical = getRValueReferenceType(getCanonicalType(T));
1138
1139 // Get the new insert position for the node we care about.
1140 RValueReferenceType *NewIP =
1141 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1142 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1143 }
1144
1145 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1146 Types.push_back(New);
1147 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 return QualType(New, 0);
1149}
1150
Sebastian Redlf30208a2009-01-24 21:16:55 +00001151/// getMemberPointerType - Return the uniqued reference to the type for a
1152/// member pointer to the specified type, in the specified class.
1153QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1154{
1155 // Unique pointers, to guarantee there is only one pointer of a particular
1156 // structure.
1157 llvm::FoldingSetNodeID ID;
1158 MemberPointerType::Profile(ID, T, Cls);
1159
1160 void *InsertPos = 0;
1161 if (MemberPointerType *PT =
1162 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1163 return QualType(PT, 0);
1164
1165 // If the pointee or class type isn't canonical, this won't be a canonical
1166 // type either, so fill in the canonical type field.
1167 QualType Canonical;
1168 if (!T->isCanonical()) {
1169 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1170
1171 // Get the new insert position for the node we care about.
1172 MemberPointerType *NewIP =
1173 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1174 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1175 }
Steve Narofff83820b2009-01-27 22:08:43 +00001176 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001177 Types.push_back(New);
1178 MemberPointerTypes.InsertNode(New, InsertPos);
1179 return QualType(New, 0);
1180}
1181
Steve Narofffb22d962007-08-30 01:06:46 +00001182/// getConstantArrayType - Return the unique reference to the type for an
1183/// array of the specified element type.
1184QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001185 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001186 ArrayType::ArraySizeModifier ASM,
1187 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001188 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1189 "Constant array of VLAs is illegal!");
1190
Chris Lattner38aeec72009-05-13 04:12:56 +00001191 // Convert the array size into a canonical width matching the pointer size for
1192 // the target.
1193 llvm::APInt ArySize(ArySizeIn);
1194 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1195
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001197 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198
1199 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001200 if (ConstantArrayType *ATP =
1201 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 return QualType(ATP, 0);
1203
1204 // If the element type isn't canonical, this won't be a canonical type either,
1205 // so fill in the canonical type field.
1206 QualType Canonical;
1207 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001208 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001209 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001211 ConstantArrayType *NewIP =
1212 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001213 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 }
1215
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001216 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001217 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001218 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 Types.push_back(New);
1220 return QualType(New, 0);
1221}
1222
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001223/// getConstantArrayWithExprType - Return a reference to the type for
1224/// an array of the specified element type.
1225QualType
1226ASTContext::getConstantArrayWithExprType(QualType EltTy,
1227 const llvm::APInt &ArySizeIn,
1228 Expr *ArySizeExpr,
1229 ArrayType::ArraySizeModifier ASM,
1230 unsigned EltTypeQuals,
1231 SourceRange Brackets) {
1232 // Convert the array size into a canonical width matching the pointer
1233 // size for the target.
1234 llvm::APInt ArySize(ArySizeIn);
1235 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1236
1237 // Compute the canonical ConstantArrayType.
1238 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1239 ArySize, ASM, EltTypeQuals);
1240 // Since we don't unique expressions, it isn't possible to unique VLA's
1241 // that have an expression provided for their size.
1242 ConstantArrayWithExprType *New =
1243 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1244 ArySize, ArySizeExpr,
1245 ASM, EltTypeQuals, Brackets);
1246 Types.push_back(New);
1247 return QualType(New, 0);
1248}
1249
1250/// getConstantArrayWithoutExprType - Return a reference to the type for
1251/// an array of the specified element type.
1252QualType
1253ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1254 const llvm::APInt &ArySizeIn,
1255 ArrayType::ArraySizeModifier ASM,
1256 unsigned EltTypeQuals) {
1257 // Convert the array size into a canonical width matching the pointer
1258 // size for the target.
1259 llvm::APInt ArySize(ArySizeIn);
1260 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1261
1262 // Compute the canonical ConstantArrayType.
1263 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1264 ArySize, ASM, EltTypeQuals);
1265 ConstantArrayWithoutExprType *New =
1266 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1267 ArySize, ASM, EltTypeQuals);
1268 Types.push_back(New);
1269 return QualType(New, 0);
1270}
1271
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001272/// getVariableArrayType - Returns a non-unique reference to the type for a
1273/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001274QualType ASTContext::getVariableArrayType(QualType EltTy,
1275 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001276 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001277 unsigned EltTypeQuals,
1278 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001279 // Since we don't unique expressions, it isn't possible to unique VLA's
1280 // that have an expression provided for their size.
1281
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001282 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001283 new(*this,8)VariableArrayType(EltTy, QualType(),
1284 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001285
1286 VariableArrayTypes.push_back(New);
1287 Types.push_back(New);
1288 return QualType(New, 0);
1289}
1290
Douglas Gregor898574e2008-12-05 23:32:09 +00001291/// getDependentSizedArrayType - Returns a non-unique reference to
1292/// the type for a dependently-sized array of the specified element
1293/// type. FIXME: We will need these to be uniqued, or at least
1294/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001295QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1296 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001297 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001298 unsigned EltTypeQuals,
1299 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001300 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1301 "Size must be type- or value-dependent!");
1302
1303 // Since we don't unique expressions, it isn't possible to unique
1304 // dependently-sized array types.
1305
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001306 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001307 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1308 NumElts, ASM, EltTypeQuals,
1309 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001310
1311 DependentSizedArrayTypes.push_back(New);
1312 Types.push_back(New);
1313 return QualType(New, 0);
1314}
1315
Eli Friedmanc5773c42008-02-15 18:16:39 +00001316QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1317 ArrayType::ArraySizeModifier ASM,
1318 unsigned EltTypeQuals) {
1319 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001320 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001321
1322 void *InsertPos = 0;
1323 if (IncompleteArrayType *ATP =
1324 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1325 return QualType(ATP, 0);
1326
1327 // If the element type isn't canonical, this won't be a canonical type
1328 // either, so fill in the canonical type field.
1329 QualType Canonical;
1330
1331 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001332 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001333 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001334
1335 // Get the new insert position for the node we care about.
1336 IncompleteArrayType *NewIP =
1337 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001338 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001339 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001340
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001341 IncompleteArrayType *New
1342 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1343 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001344
1345 IncompleteArrayTypes.InsertNode(New, InsertPos);
1346 Types.push_back(New);
1347 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001348}
1349
Steve Naroff73322922007-07-18 18:00:27 +00001350/// getVectorType - Return the unique reference to a vector type of
1351/// the specified element type and size. VectorType must be a built-in type.
1352QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 BuiltinType *baseType;
1354
Chris Lattnerf52ab252008-04-06 22:59:24 +00001355 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001356 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001357
1358 // Check if we've already instantiated a vector of this type.
1359 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001360 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 void *InsertPos = 0;
1362 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1363 return QualType(VTP, 0);
1364
1365 // If the element type isn't canonical, this won't be a canonical type either,
1366 // so fill in the canonical type field.
1367 QualType Canonical;
1368 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001369 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001370
1371 // Get the new insert position for the node we care about.
1372 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001373 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 }
Steve Narofff83820b2009-01-27 22:08:43 +00001375 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 VectorTypes.InsertNode(New, InsertPos);
1377 Types.push_back(New);
1378 return QualType(New, 0);
1379}
1380
Nate Begeman213541a2008-04-18 23:10:10 +00001381/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001382/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001383QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001384 BuiltinType *baseType;
1385
Chris Lattnerf52ab252008-04-06 22:59:24 +00001386 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001387 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001388
1389 // Check if we've already instantiated a vector of this type.
1390 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001391 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001392 void *InsertPos = 0;
1393 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1394 return QualType(VTP, 0);
1395
1396 // If the element type isn't canonical, this won't be a canonical type either,
1397 // so fill in the canonical type field.
1398 QualType Canonical;
1399 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001400 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001401
1402 // Get the new insert position for the node we care about.
1403 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001404 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001405 }
Steve Narofff83820b2009-01-27 22:08:43 +00001406 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001407 VectorTypes.InsertNode(New, InsertPos);
1408 Types.push_back(New);
1409 return QualType(New, 0);
1410}
1411
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001412QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1413 Expr *SizeExpr,
1414 SourceLocation AttrLoc) {
1415 DependentSizedExtVectorType *New =
1416 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1417 SizeExpr, AttrLoc);
1418
1419 DependentSizedExtVectorTypes.push_back(New);
1420 Types.push_back(New);
1421 return QualType(New, 0);
1422}
1423
Douglas Gregor72564e72009-02-26 23:50:07 +00001424/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001425///
Douglas Gregor72564e72009-02-26 23:50:07 +00001426QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 // Unique functions, to guarantee there is only one function of a particular
1428 // structure.
1429 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001430 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001431
1432 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001433 if (FunctionNoProtoType *FT =
1434 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 return QualType(FT, 0);
1436
1437 QualType Canonical;
1438 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001439 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001440
1441 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001442 FunctionNoProtoType *NewIP =
1443 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001444 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 }
1446
Douglas Gregor72564e72009-02-26 23:50:07 +00001447 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001449 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 return QualType(New, 0);
1451}
1452
1453/// getFunctionType - Return a normal function type with a typed argument
1454/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001455QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001456 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001457 unsigned TypeQuals, bool hasExceptionSpec,
1458 bool hasAnyExceptionSpec, unsigned NumExs,
1459 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 // Unique functions, to guarantee there is only one function of a particular
1461 // structure.
1462 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001463 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001464 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1465 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001466
1467 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001468 if (FunctionProtoType *FTP =
1469 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001471
1472 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001474 if (hasExceptionSpec)
1475 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1477 if (!ArgArray[i]->isCanonical())
1478 isCanonical = false;
1479
1480 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001481 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 QualType Canonical;
1483 if (!isCanonical) {
1484 llvm::SmallVector<QualType, 16> CanonicalArgs;
1485 CanonicalArgs.reserve(NumArgs);
1486 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001487 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001488
Chris Lattnerf52ab252008-04-06 22:59:24 +00001489 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001490 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001491 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001492
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001494 FunctionProtoType *NewIP =
1495 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001496 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001498
Douglas Gregor72564e72009-02-26 23:50:07 +00001499 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001500 // for two variable size arrays (for parameter and exception types) at the
1501 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001502 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001503 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1504 NumArgs*sizeof(QualType) +
1505 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001506 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001507 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1508 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001510 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 return QualType(FTP, 0);
1512}
1513
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001514/// getTypeDeclType - Return the unique reference to the type for the
1515/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001516QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001517 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001518 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1519
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001520 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001521 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001522 else if (isa<TemplateTypeParmDecl>(Decl)) {
1523 assert(false && "Template type parameter types are always available.");
1524 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001525 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001526
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001527 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001528 if (PrevDecl)
1529 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001530 else
1531 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001532 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001533 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1534 if (PrevDecl)
1535 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001536 else
1537 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001538 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001539 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001540 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001541
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001542 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001543 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001544}
1545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546/// getTypedefType - Return the unique reference to the type for the
1547/// specified typename decl.
1548QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1549 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1550
Chris Lattnerf52ab252008-04-06 22:59:24 +00001551 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001552 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 Types.push_back(Decl->TypeForDecl);
1554 return QualType(Decl->TypeForDecl, 0);
1555}
1556
Douglas Gregorfab9d672009-02-05 23:33:38 +00001557/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001558/// parameter or parameter pack with the given depth, index, and (optionally)
1559/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001560QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001561 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001562 IdentifierInfo *Name) {
1563 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001564 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001565 void *InsertPos = 0;
1566 TemplateTypeParmType *TypeParm
1567 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1568
1569 if (TypeParm)
1570 return QualType(TypeParm, 0);
1571
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001572 if (Name) {
1573 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1574 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1575 Name, Canon);
1576 } else
1577 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001578
1579 Types.push_back(TypeParm);
1580 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1581
1582 return QualType(TypeParm, 0);
1583}
1584
Douglas Gregor55f6b142009-02-09 18:46:07 +00001585QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001586ASTContext::getTemplateSpecializationType(TemplateName Template,
1587 const TemplateArgument *Args,
1588 unsigned NumArgs,
1589 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001590 if (!Canon.isNull())
1591 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001592
Douglas Gregor55f6b142009-02-09 18:46:07 +00001593 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001594 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001595
Douglas Gregor55f6b142009-02-09 18:46:07 +00001596 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001597 TemplateSpecializationType *Spec
1598 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001599
1600 if (Spec)
1601 return QualType(Spec, 0);
1602
Douglas Gregor7532dc62009-03-30 22:58:21 +00001603 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001604 sizeof(TemplateArgument) * NumArgs),
1605 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001606 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001607 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001608 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001609
1610 return QualType(Spec, 0);
1611}
1612
Douglas Gregore4e5b052009-03-19 00:18:19 +00001613QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001614ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001615 QualType NamedType) {
1616 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001617 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001618
1619 void *InsertPos = 0;
1620 QualifiedNameType *T
1621 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1622 if (T)
1623 return QualType(T, 0);
1624
Douglas Gregorab452ba2009-03-26 23:50:42 +00001625 T = new (*this) QualifiedNameType(NNS, NamedType,
1626 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001627 Types.push_back(T);
1628 QualifiedNameTypes.InsertNode(T, InsertPos);
1629 return QualType(T, 0);
1630}
1631
Douglas Gregord57959a2009-03-27 23:10:48 +00001632QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1633 const IdentifierInfo *Name,
1634 QualType Canon) {
1635 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1636
1637 if (Canon.isNull()) {
1638 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1639 if (CanonNNS != NNS)
1640 Canon = getTypenameType(CanonNNS, Name);
1641 }
1642
1643 llvm::FoldingSetNodeID ID;
1644 TypenameType::Profile(ID, NNS, Name);
1645
1646 void *InsertPos = 0;
1647 TypenameType *T
1648 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1649 if (T)
1650 return QualType(T, 0);
1651
1652 T = new (*this) TypenameType(NNS, Name, Canon);
1653 Types.push_back(T);
1654 TypenameTypes.InsertNode(T, InsertPos);
1655 return QualType(T, 0);
1656}
1657
Douglas Gregor17343172009-04-01 00:28:59 +00001658QualType
1659ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1660 const TemplateSpecializationType *TemplateId,
1661 QualType Canon) {
1662 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1663
1664 if (Canon.isNull()) {
1665 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1666 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1667 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1668 const TemplateSpecializationType *CanonTemplateId
1669 = CanonType->getAsTemplateSpecializationType();
1670 assert(CanonTemplateId &&
1671 "Canonical type must also be a template specialization type");
1672 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1673 }
1674 }
1675
1676 llvm::FoldingSetNodeID ID;
1677 TypenameType::Profile(ID, NNS, TemplateId);
1678
1679 void *InsertPos = 0;
1680 TypenameType *T
1681 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1682 if (T)
1683 return QualType(T, 0);
1684
1685 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1686 Types.push_back(T);
1687 TypenameTypes.InsertNode(T, InsertPos);
1688 return QualType(T, 0);
1689}
1690
Chris Lattner88cb27a2008-04-07 04:56:42 +00001691/// CmpProtocolNames - Comparison predicate for sorting protocols
1692/// alphabetically.
1693static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1694 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001695 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001696}
1697
1698static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1699 unsigned &NumProtocols) {
1700 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1701
1702 // Sort protocols, keyed by name.
1703 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1704
1705 // Remove duplicates.
1706 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1707 NumProtocols = ProtocolsEnd-Protocols;
1708}
1709
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001710/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1711/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001712QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001713 ObjCProtocolDecl **Protocols,
1714 unsigned NumProtocols) {
Steve Naroff14108da2009-07-10 23:34:53 +00001715 if (InterfaceT.isNull())
Steve Naroffde2e22d2009-07-15 18:40:39 +00001716 InterfaceT = ObjCBuiltinIdTy;
Steve Naroff14108da2009-07-10 23:34:53 +00001717
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001718 // Sort the protocol list alphabetically to canonicalize it.
1719 if (NumProtocols)
1720 SortAndUniqueProtocols(Protocols, NumProtocols);
1721
1722 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001723 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001724
1725 void *InsertPos = 0;
1726 if (ObjCObjectPointerType *QT =
1727 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1728 return QualType(QT, 0);
1729
1730 // No Match;
1731 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001732 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001733
1734 Types.push_back(QType);
1735 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1736 return QualType(QType, 0);
1737}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001738
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001739/// getObjCInterfaceType - Return the unique reference to the type for the
1740/// specified ObjC interface decl. The list of protocols is optional.
1741QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001742 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001743 if (NumProtocols)
1744 // Sort the protocol list alphabetically to canonicalize it.
1745 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001746
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001747 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001748 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001749
1750 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001751 if (ObjCInterfaceType *QT =
1752 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001753 return QualType(QT, 0);
1754
1755 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001756 ObjCInterfaceType *QType =
1757 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1758 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001759 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001760 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001761 return QualType(QType, 0);
1762}
1763
Douglas Gregor72564e72009-02-26 23:50:07 +00001764/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1765/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001766/// multiple declarations that refer to "typeof(x)" all contain different
1767/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1768/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001769QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001770 TypeOfExprType *toe;
1771 if (tofExpr->isTypeDependent())
1772 toe = new (*this, 8) TypeOfExprType(tofExpr);
1773 else {
1774 QualType Canonical = getCanonicalType(tofExpr->getType());
1775 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1776 }
Steve Naroff9752f252007-08-01 18:02:17 +00001777 Types.push_back(toe);
1778 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001779}
1780
Steve Naroff9752f252007-08-01 18:02:17 +00001781/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1782/// TypeOfType AST's. The only motivation to unique these nodes would be
1783/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1784/// an issue. This doesn't effect the type checker, since it operates
1785/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001786QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001787 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001788 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001789 Types.push_back(tot);
1790 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001791}
1792
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001793/// getDecltypeForExpr - Given an expr, will return the decltype for that
1794/// expression, according to the rules in C++0x [dcl.type.simple]p4
1795static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001796 if (e->isTypeDependent())
1797 return Context.DependentTy;
1798
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001799 // If e is an id expression or a class member access, decltype(e) is defined
1800 // as the type of the entity named by e.
1801 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1802 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1803 return VD->getType();
1804 }
1805 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1806 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1807 return FD->getType();
1808 }
1809 // If e is a function call or an invocation of an overloaded operator,
1810 // (parentheses around e are ignored), decltype(e) is defined as the
1811 // return type of that function.
1812 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1813 return CE->getCallReturnType();
1814
1815 QualType T = e->getType();
1816
1817 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1818 // defined as T&, otherwise decltype(e) is defined as T.
1819 if (e->isLvalue(Context) == Expr::LV_Valid)
1820 T = Context.getLValueReferenceType(T);
1821
1822 return T;
1823}
1824
Anders Carlsson395b4752009-06-24 19:06:50 +00001825/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1826/// DecltypeType AST's. The only motivation to unique these nodes would be
1827/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1828/// an issue. This doesn't effect the type checker, since it operates
1829/// on canonical type's (which are always unique).
1830QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001831 DecltypeType *dt;
1832 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson563a03b2009-07-10 19:20:26 +00001833 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregordd0257c2009-07-08 00:03:05 +00001834 else {
1835 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00001836 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00001837 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001838 Types.push_back(dt);
1839 return QualType(dt, 0);
1840}
1841
Reid Spencer5f016e22007-07-11 17:01:13 +00001842/// getTagDeclType - Return the unique reference to the type for the
1843/// specified TagDecl (struct/union/class/enum) decl.
1844QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001845 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001846 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001847}
1848
1849/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1850/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1851/// needs to agree with the definition in <stddef.h>.
1852QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001853 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001854}
1855
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001856/// getSignedWCharType - Return the type of "signed wchar_t".
1857/// Used when in C++, as a GCC extension.
1858QualType ASTContext::getSignedWCharType() const {
1859 // FIXME: derive from "Target" ?
1860 return WCharTy;
1861}
1862
1863/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1864/// Used when in C++, as a GCC extension.
1865QualType ASTContext::getUnsignedWCharType() const {
1866 // FIXME: derive from "Target" ?
1867 return UnsignedIntTy;
1868}
1869
Chris Lattner8b9023b2007-07-13 03:05:23 +00001870/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1871/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1872QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001873 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001874}
1875
Chris Lattnere6327742008-04-02 05:18:44 +00001876//===----------------------------------------------------------------------===//
1877// Type Operators
1878//===----------------------------------------------------------------------===//
1879
Chris Lattner77c96472008-04-06 22:41:35 +00001880/// getCanonicalType - Return the canonical (structural) type corresponding to
1881/// the specified potentially non-canonical type. The non-canonical version
1882/// of a type may have many "decorated" versions of types. Decorators can
1883/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1884/// to be free of any of these, allowing two canonical types to be compared
1885/// for exact equality with a simple pointer comparison.
1886QualType ASTContext::getCanonicalType(QualType T) {
1887 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001888
1889 // If the result has type qualifiers, make sure to canonicalize them as well.
1890 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1891 if (TypeQuals == 0) return CanType;
1892
1893 // If the type qualifiers are on an array type, get the canonical type of the
1894 // array with the qualifiers applied to the element type.
1895 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1896 if (!AT)
1897 return CanType.getQualifiedType(TypeQuals);
1898
1899 // Get the canonical version of the element with the extra qualifiers on it.
1900 // This can recursively sink qualifiers through multiple levels of arrays.
1901 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1902 NewEltTy = getCanonicalType(NewEltTy);
1903
1904 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1905 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1906 CAT->getIndexTypeQualifier());
1907 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1908 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1909 IAT->getIndexTypeQualifier());
1910
Douglas Gregor898574e2008-12-05 23:32:09 +00001911 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001912 return getDependentSizedArrayType(NewEltTy,
1913 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00001914 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001915 DSAT->getIndexTypeQualifier(),
1916 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00001917
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001918 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001919 return getVariableArrayType(NewEltTy,
1920 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001921 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001922 VAT->getIndexTypeQualifier(),
1923 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001924}
1925
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001926TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1927 // If this template name refers to a template, the canonical
1928 // template name merely stores the template itself.
1929 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001930 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001931
1932 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1933 assert(DTN && "Non-dependent template names must refer to template decls.");
1934 return DTN->CanonicalTemplateName;
1935}
1936
Douglas Gregord57959a2009-03-27 23:10:48 +00001937NestedNameSpecifier *
1938ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1939 if (!NNS)
1940 return 0;
1941
1942 switch (NNS->getKind()) {
1943 case NestedNameSpecifier::Identifier:
1944 // Canonicalize the prefix but keep the identifier the same.
1945 return NestedNameSpecifier::Create(*this,
1946 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1947 NNS->getAsIdentifier());
1948
1949 case NestedNameSpecifier::Namespace:
1950 // A namespace is canonical; build a nested-name-specifier with
1951 // this namespace and no prefix.
1952 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1953
1954 case NestedNameSpecifier::TypeSpec:
1955 case NestedNameSpecifier::TypeSpecWithTemplate: {
1956 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1957 NestedNameSpecifier *Prefix = 0;
1958
1959 // FIXME: This isn't the right check!
1960 if (T->isDependentType())
1961 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1962
1963 return NestedNameSpecifier::Create(*this, Prefix,
1964 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1965 T.getTypePtr());
1966 }
1967
1968 case NestedNameSpecifier::Global:
1969 // The global specifier is canonical and unique.
1970 return NNS;
1971 }
1972
1973 // Required to silence a GCC warning
1974 return 0;
1975}
1976
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001977
1978const ArrayType *ASTContext::getAsArrayType(QualType T) {
1979 // Handle the non-qualified case efficiently.
1980 if (T.getCVRQualifiers() == 0) {
1981 // Handle the common positive case fast.
1982 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1983 return AT;
1984 }
1985
1986 // Handle the common negative case fast, ignoring CVR qualifiers.
1987 QualType CType = T->getCanonicalTypeInternal();
1988
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001989 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001990 // test.
1991 if (!isa<ArrayType>(CType) &&
1992 !isa<ArrayType>(CType.getUnqualifiedType()))
1993 return 0;
1994
1995 // Apply any CVR qualifiers from the array type to the element type. This
1996 // implements C99 6.7.3p8: "If the specification of an array type includes
1997 // any type qualifiers, the element type is so qualified, not the array type."
1998
1999 // If we get here, we either have type qualifiers on the type, or we have
2000 // sugar such as a typedef in the way. If we have type qualifiers on the type
2001 // we must propagate them down into the elemeng type.
2002 unsigned CVRQuals = T.getCVRQualifiers();
2003 unsigned AddrSpace = 0;
2004 Type *Ty = T.getTypePtr();
2005
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002006 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002007 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002008 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2009 AddrSpace = EXTQT->getAddressSpace();
2010 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002011 } else {
2012 T = Ty->getDesugaredType();
2013 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2014 break;
2015 CVRQuals |= T.getCVRQualifiers();
2016 Ty = T.getTypePtr();
2017 }
2018 }
2019
2020 // If we have a simple case, just return now.
2021 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2022 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2023 return ATy;
2024
2025 // Otherwise, we have an array and we have qualifiers on it. Push the
2026 // qualifiers into the array element type and return a new array type.
2027 // Get the canonical version of the element with the extra qualifiers on it.
2028 // This can recursively sink qualifiers through multiple levels of arrays.
2029 QualType NewEltTy = ATy->getElementType();
2030 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002031 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002032 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2033
2034 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2035 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2036 CAT->getSizeModifier(),
2037 CAT->getIndexTypeQualifier()));
2038 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2039 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2040 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002041 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002042
Douglas Gregor898574e2008-12-05 23:32:09 +00002043 if (const DependentSizedArrayType *DSAT
2044 = dyn_cast<DependentSizedArrayType>(ATy))
2045 return cast<ArrayType>(
2046 getDependentSizedArrayType(NewEltTy,
2047 DSAT->getSizeExpr(),
2048 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002049 DSAT->getIndexTypeQualifier(),
2050 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002051
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002052 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002053 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2054 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002055 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002056 VAT->getIndexTypeQualifier(),
2057 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002058}
2059
2060
Chris Lattnere6327742008-04-02 05:18:44 +00002061/// getArrayDecayedType - Return the properly qualified result of decaying the
2062/// specified array type to a pointer. This operation is non-trivial when
2063/// handling typedefs etc. The canonical type of "T" must be an array type,
2064/// this returns a pointer to a properly qualified element of the array.
2065///
2066/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2067QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002068 // Get the element type with 'getAsArrayType' so that we don't lose any
2069 // typedefs in the element type of the array. This also handles propagation
2070 // of type qualifiers from the array type into the element type if present
2071 // (C99 6.7.3p8).
2072 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2073 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002074
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002075 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002076
2077 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002078 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002079}
2080
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002081QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002082 QualType ElemTy = VAT->getElementType();
2083
2084 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2085 return getBaseElementType(VAT);
2086
2087 return ElemTy;
2088}
2089
Reid Spencer5f016e22007-07-11 17:01:13 +00002090/// getFloatingRank - Return a relative rank for floating point types.
2091/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002092static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002093 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002095
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002096 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002097 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002098 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 case BuiltinType::Float: return FloatRank;
2100 case BuiltinType::Double: return DoubleRank;
2101 case BuiltinType::LongDouble: return LongDoubleRank;
2102 }
2103}
2104
Steve Naroff716c7302007-08-27 01:41:48 +00002105/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2106/// point or a complex type (based on typeDomain/typeSize).
2107/// 'typeDomain' is a real floating point or complex type.
2108/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002109QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2110 QualType Domain) const {
2111 FloatingRank EltRank = getFloatingRank(Size);
2112 if (Domain->isComplexType()) {
2113 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002114 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002115 case FloatRank: return FloatComplexTy;
2116 case DoubleRank: return DoubleComplexTy;
2117 case LongDoubleRank: return LongDoubleComplexTy;
2118 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 }
Chris Lattner1361b112008-04-06 23:58:54 +00002120
2121 assert(Domain->isRealFloatingType() && "Unknown domain!");
2122 switch (EltRank) {
2123 default: assert(0 && "getFloatingRank(): illegal value for rank");
2124 case FloatRank: return FloatTy;
2125 case DoubleRank: return DoubleTy;
2126 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002128}
2129
Chris Lattner7cfeb082008-04-06 23:55:33 +00002130/// getFloatingTypeOrder - Compare the rank of the two specified floating
2131/// point types, ignoring the domain of the type (i.e. 'double' ==
2132/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2133/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002134int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2135 FloatingRank LHSR = getFloatingRank(LHS);
2136 FloatingRank RHSR = getFloatingRank(RHS);
2137
2138 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002139 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002140 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002141 return 1;
2142 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002143}
2144
Chris Lattnerf52ab252008-04-06 22:59:24 +00002145/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2146/// routine will assert if passed a built-in type that isn't an integer or enum,
2147/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002148unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002149 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002150 if (EnumType* ET = dyn_cast<EnumType>(T))
2151 T = ET->getDecl()->getIntegerType().getTypePtr();
2152
Eli Friedmana3426752009-07-05 23:44:27 +00002153 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2154 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2155
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002156 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2157 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2158
2159 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2160 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2161
Eli Friedmanf98aba32009-02-13 02:31:07 +00002162 // There are two things which impact the integer rank: the width, and
2163 // the ordering of builtins. The builtin ordering is encoded in the
2164 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002165 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002166 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002167
Chris Lattnerf52ab252008-04-06 22:59:24 +00002168 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002169 default: assert(0 && "getIntegerRank(): not a built-in integer");
2170 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002171 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002172 case BuiltinType::Char_S:
2173 case BuiltinType::Char_U:
2174 case BuiltinType::SChar:
2175 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002176 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002177 case BuiltinType::Short:
2178 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002179 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002180 case BuiltinType::Int:
2181 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002182 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002183 case BuiltinType::Long:
2184 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002185 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002186 case BuiltinType::LongLong:
2187 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002188 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002189 case BuiltinType::Int128:
2190 case BuiltinType::UInt128:
2191 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002192 }
2193}
2194
Chris Lattner7cfeb082008-04-06 23:55:33 +00002195/// getIntegerTypeOrder - Returns the highest ranked integer type:
2196/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2197/// LHS < RHS, return -1.
2198int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002199 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2200 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002201 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202
Chris Lattnerf52ab252008-04-06 22:59:24 +00002203 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2204 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002205
Chris Lattner7cfeb082008-04-06 23:55:33 +00002206 unsigned LHSRank = getIntegerRank(LHSC);
2207 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002208
Chris Lattner7cfeb082008-04-06 23:55:33 +00002209 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2210 if (LHSRank == RHSRank) return 0;
2211 return LHSRank > RHSRank ? 1 : -1;
2212 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002213
Chris Lattner7cfeb082008-04-06 23:55:33 +00002214 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2215 if (LHSUnsigned) {
2216 // If the unsigned [LHS] type is larger, return it.
2217 if (LHSRank >= RHSRank)
2218 return 1;
2219
2220 // If the signed type can represent all values of the unsigned type, it
2221 // wins. Because we are dealing with 2's complement and types that are
2222 // powers of two larger than each other, this is always safe.
2223 return -1;
2224 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002225
Chris Lattner7cfeb082008-04-06 23:55:33 +00002226 // If the unsigned [RHS] type is larger, return it.
2227 if (RHSRank >= LHSRank)
2228 return -1;
2229
2230 // If the signed type can represent all values of the unsigned type, it
2231 // wins. Because we are dealing with 2's complement and types that are
2232 // powers of two larger than each other, this is always safe.
2233 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002234}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002235
2236// getCFConstantStringType - Return the type used for constant CFStrings.
2237QualType ASTContext::getCFConstantStringType() {
2238 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002239 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002240 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002241 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002242 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002243
2244 // const int *isa;
2245 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002246 // int flags;
2247 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002248 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002249 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002250 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002251 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002252
Anders Carlsson71993dd2007-08-17 05:31:46 +00002253 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002254 for (unsigned i = 0; i < 4; ++i) {
2255 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2256 SourceLocation(), 0,
2257 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002258 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002259 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002260 }
2261
2262 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002263 }
2264
2265 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002266}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002267
Douglas Gregor319ac892009-04-23 22:29:11 +00002268void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002269 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002270 assert(Rec && "Invalid CFConstantStringType");
2271 CFConstantStringTypeDecl = Rec->getDecl();
2272}
2273
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002274QualType ASTContext::getObjCFastEnumerationStateType()
2275{
2276 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002277 ObjCFastEnumerationStateTypeDecl =
2278 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2279 &Idents.get("__objcFastEnumerationState"));
2280
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002281 QualType FieldTypes[] = {
2282 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002283 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002284 getPointerType(UnsignedLongTy),
2285 getConstantArrayType(UnsignedLongTy,
2286 llvm::APInt(32, 5), ArrayType::Normal, 0)
2287 };
2288
Douglas Gregor44b43212008-12-11 16:49:14 +00002289 for (size_t i = 0; i < 4; ++i) {
2290 FieldDecl *Field = FieldDecl::Create(*this,
2291 ObjCFastEnumerationStateTypeDecl,
2292 SourceLocation(), 0,
2293 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002294 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002295 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002296 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002297
Douglas Gregor44b43212008-12-11 16:49:14 +00002298 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002299 }
2300
2301 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2302}
2303
Douglas Gregor319ac892009-04-23 22:29:11 +00002304void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002305 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002306 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2307 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2308}
2309
Anders Carlssone8c49532007-10-29 06:33:42 +00002310// This returns true if a type has been typedefed to BOOL:
2311// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002312static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002313 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002314 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2315 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002316
2317 return false;
2318}
2319
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002320/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002321/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002322int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002323 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002324
2325 // Make all integer and enum types at least as large as an int
2326 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002327 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002328 // Treat arrays as pointers, since that's how they're passed in.
2329 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002330 sz = getTypeSize(VoidPtrTy);
2331 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002332}
2333
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002334/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002335/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002336void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002337 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002338 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002339 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002340 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002341 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002342 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002343 // Compute size of all parameters.
2344 // Start with computing size of a pointer in number of bytes.
2345 // FIXME: There might(should) be a better way of doing this computation!
2346 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002347 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002348 // The first two arguments (self and _cmd) are pointers; account for
2349 // their size.
2350 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002351 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2352 E = Decl->param_end(); PI != E; ++PI) {
2353 QualType PType = (*PI)->getType();
2354 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002355 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002356 ParmOffset += sz;
2357 }
2358 S += llvm::utostr(ParmOffset);
2359 S += "@0:";
2360 S += llvm::utostr(PtrSize);
2361
2362 // Argument types.
2363 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002364 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2365 E = Decl->param_end(); PI != E; ++PI) {
2366 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002367 QualType PType = PVDecl->getOriginalType();
2368 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002369 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2370 // Use array's original type only if it has known number of
2371 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002372 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002373 PType = PVDecl->getType();
2374 } else if (PType->isFunctionType())
2375 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002376 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002377 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002378 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002379 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002380 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002382 }
2383}
2384
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002385/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002386/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002387/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2388/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002389/// Property attributes are stored as a comma-delimited C string. The simple
2390/// attributes readonly and bycopy are encoded as single characters. The
2391/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2392/// encoded as single characters, followed by an identifier. Property types
2393/// are also encoded as a parametrized attribute. The characters used to encode
2394/// these attributes are defined by the following enumeration:
2395/// @code
2396/// enum PropertyAttributes {
2397/// kPropertyReadOnly = 'R', // property is read-only.
2398/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2399/// kPropertyByref = '&', // property is a reference to the value last assigned
2400/// kPropertyDynamic = 'D', // property is dynamic
2401/// kPropertyGetter = 'G', // followed by getter selector name
2402/// kPropertySetter = 'S', // followed by setter selector name
2403/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2404/// kPropertyType = 't' // followed by old-style type encoding.
2405/// kPropertyWeak = 'W' // 'weak' property
2406/// kPropertyStrong = 'P' // property GC'able
2407/// kPropertyNonAtomic = 'N' // property non-atomic
2408/// };
2409/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002410void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2411 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002412 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002413 // Collect information from the property implementation decl(s).
2414 bool Dynamic = false;
2415 ObjCPropertyImplDecl *SynthesizePID = 0;
2416
2417 // FIXME: Duplicated code due to poor abstraction.
2418 if (Container) {
2419 if (const ObjCCategoryImplDecl *CID =
2420 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2421 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002422 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002423 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002424 ObjCPropertyImplDecl *PID = *i;
2425 if (PID->getPropertyDecl() == PD) {
2426 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2427 Dynamic = true;
2428 } else {
2429 SynthesizePID = PID;
2430 }
2431 }
2432 }
2433 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002434 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002435 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002436 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002437 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002438 ObjCPropertyImplDecl *PID = *i;
2439 if (PID->getPropertyDecl() == PD) {
2440 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2441 Dynamic = true;
2442 } else {
2443 SynthesizePID = PID;
2444 }
2445 }
2446 }
2447 }
2448 }
2449
2450 // FIXME: This is not very efficient.
2451 S = "T";
2452
2453 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002454 // GCC has some special rules regarding encoding of properties which
2455 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002456 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002457 true /* outermost type */,
2458 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002459
2460 if (PD->isReadOnly()) {
2461 S += ",R";
2462 } else {
2463 switch (PD->getSetterKind()) {
2464 case ObjCPropertyDecl::Assign: break;
2465 case ObjCPropertyDecl::Copy: S += ",C"; break;
2466 case ObjCPropertyDecl::Retain: S += ",&"; break;
2467 }
2468 }
2469
2470 // It really isn't clear at all what this means, since properties
2471 // are "dynamic by default".
2472 if (Dynamic)
2473 S += ",D";
2474
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002475 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2476 S += ",N";
2477
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002478 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2479 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002480 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002481 }
2482
2483 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2484 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002485 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002486 }
2487
2488 if (SynthesizePID) {
2489 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2490 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002491 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002492 }
2493
2494 // FIXME: OBJCGC: weak & strong
2495}
2496
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002497/// getLegacyIntegralTypeEncoding -
2498/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002499/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002500/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2501///
2502void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2503 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2504 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002505 if (BT->getKind() == BuiltinType::ULong &&
2506 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002507 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002508 else
2509 if (BT->getKind() == BuiltinType::Long &&
2510 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002511 PointeeTy = IntTy;
2512 }
2513 }
2514}
2515
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002516void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002517 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002518 // We follow the behavior of gcc, expanding structures which are
2519 // directly pointed to, and expanding embedded structures. Note that
2520 // these rules are sufficient to prevent recursive encoding of the
2521 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002522 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2523 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002524}
2525
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002526static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002527 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002528 const Expr *E = FD->getBitWidth();
2529 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2530 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002531 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002532 S += 'b';
2533 S += llvm::utostr(N);
2534}
2535
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002536void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2537 bool ExpandPointedToStructures,
2538 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002539 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002540 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002541 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002542 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002543 if (FD && FD->isBitField())
2544 return EncodeBitField(this, S, FD);
2545 char encoding;
2546 switch (BT->getKind()) {
2547 default: assert(0 && "Unhandled builtin type kind");
2548 case BuiltinType::Void: encoding = 'v'; break;
2549 case BuiltinType::Bool: encoding = 'B'; break;
2550 case BuiltinType::Char_U:
2551 case BuiltinType::UChar: encoding = 'C'; break;
2552 case BuiltinType::UShort: encoding = 'S'; break;
2553 case BuiltinType::UInt: encoding = 'I'; break;
2554 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002555 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002556 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002557 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002558 case BuiltinType::UInt128: encoding = 'T'; break;
2559 case BuiltinType::ULongLong: encoding = 'Q'; break;
2560 case BuiltinType::Char_S:
2561 case BuiltinType::SChar: encoding = 'c'; break;
2562 case BuiltinType::Short: encoding = 's'; break;
2563 case BuiltinType::Int: encoding = 'i'; break;
2564 case BuiltinType::Long:
2565 encoding =
2566 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2567 break;
2568 case BuiltinType::LongLong: encoding = 'q'; break;
2569 case BuiltinType::Int128: encoding = 't'; break;
2570 case BuiltinType::Float: encoding = 'f'; break;
2571 case BuiltinType::Double: encoding = 'd'; break;
2572 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002573 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002574
2575 S += encoding;
2576 return;
2577 }
2578
2579 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002580 S += 'j';
2581 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2582 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002583 return;
2584 }
2585
Ted Kremenek35366a62009-07-17 17:50:17 +00002586 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002587 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002588 bool isReadOnly = false;
2589 // For historical/compatibility reasons, the read-only qualifier of the
2590 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2591 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2592 // Also, do not emit the 'r' for anything but the outermost type!
2593 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2594 if (OutermostType && T.isConstQualified()) {
2595 isReadOnly = true;
2596 S += 'r';
2597 }
2598 }
2599 else if (OutermostType) {
2600 QualType P = PointeeTy;
Ted Kremenek35366a62009-07-17 17:50:17 +00002601 while (P->getAsPointerType())
2602 P = P->getAsPointerType()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002603 if (P.isConstQualified()) {
2604 isReadOnly = true;
2605 S += 'r';
2606 }
2607 }
2608 if (isReadOnly) {
2609 // Another legacy compatibility encoding. Some ObjC qualifier and type
2610 // combinations need to be rearranged.
2611 // Rewrite "in const" from "nr" to "rn"
2612 const char * s = S.c_str();
2613 int len = S.length();
2614 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2615 std::string replace = "rn";
2616 S.replace(S.end()-2, S.end(), replace);
2617 }
2618 }
Steve Naroff14108da2009-07-10 23:34:53 +00002619 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002620 S += ':';
2621 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002622 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002623
2624 if (PointeeTy->isCharType()) {
2625 // char pointer types should be encoded as '*' unless it is a
2626 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002627 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002628 S += '*';
2629 return;
2630 }
2631 }
2632
2633 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002634 getLegacyIntegralTypeEncoding(PointeeTy);
2635
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002636 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002637 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002638 return;
2639 }
2640
2641 if (const ArrayType *AT =
2642 // Ignore type qualifiers etc.
2643 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002644 if (isa<IncompleteArrayType>(AT)) {
2645 // Incomplete arrays are encoded as a pointer to the array element.
2646 S += '^';
2647
2648 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2649 false, ExpandStructures, FD);
2650 } else {
2651 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002652
Anders Carlsson559a8332009-02-22 01:38:57 +00002653 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2654 S += llvm::utostr(CAT->getSize().getZExtValue());
2655 else {
2656 //Variable length arrays are encoded as a regular array with 0 elements.
2657 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2658 S += '0';
2659 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002660
Anders Carlsson559a8332009-02-22 01:38:57 +00002661 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2662 false, ExpandStructures, FD);
2663 S += ']';
2664 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002665 return;
2666 }
2667
2668 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002669 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002670 return;
2671 }
2672
Ted Kremenek35366a62009-07-17 17:50:17 +00002673 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002674 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002675 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002676 // Anonymous structures print as '?'
2677 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2678 S += II->getName();
2679 } else {
2680 S += '?';
2681 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002682 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002683 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002684 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2685 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002686 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002687 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002688 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002689 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002690 S += '"';
2691 }
2692
2693 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002694 if (Field->isBitField()) {
2695 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2696 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002697 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002698 QualType qt = Field->getType();
2699 getLegacyIntegralTypeEncoding(qt);
2700 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002701 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002702 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002703 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002704 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002705 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002706 return;
2707 }
2708
2709 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002710 if (FD && FD->isBitField())
2711 EncodeBitField(this, S, FD);
2712 else
2713 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002714 return;
2715 }
2716
2717 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002718 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002719 return;
2720 }
2721
2722 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002723 // @encode(class_name)
2724 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2725 S += '{';
2726 const IdentifierInfo *II = OI->getIdentifier();
2727 S += II->getName();
2728 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002729 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002730 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002731 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002732 if (RecFields[i]->isBitField())
2733 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2734 RecFields[i]);
2735 else
2736 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2737 FD);
2738 }
2739 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002740 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002741 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002742
2743 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002744 if (OPT->isObjCIdType()) {
2745 S += '@';
2746 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002747 }
2748
2749 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002750 S += '#';
2751 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002752 }
2753
2754 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002755 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2756 ExpandPointedToStructures,
2757 ExpandStructures, FD);
2758 if (FD || EncodingProperty) {
2759 // Note that we do extended encoding of protocol qualifer list
2760 // Only when doing ivar or property encoding.
2761 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2762 S += '"';
2763 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2764 E = QIDT->qual_end(); I != E; ++I) {
2765 S += '<';
2766 S += (*I)->getNameAsString();
2767 S += '>';
2768 }
2769 S += '"';
2770 }
2771 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002772 }
2773
2774 QualType PointeeTy = OPT->getPointeeType();
2775 if (!EncodingProperty &&
2776 isa<TypedefType>(PointeeTy.getTypePtr())) {
2777 // Another historical/compatibility reason.
2778 // We encode the underlying type which comes out as
2779 // {...};
2780 S += '^';
2781 getObjCEncodingForTypeImpl(PointeeTy, S,
2782 false, ExpandPointedToStructures,
2783 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00002784 return;
2785 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002786
2787 S += '@';
2788 if (FD || EncodingProperty) {
2789 const ObjCInterfaceType *OIT = OPT->getInterfaceType();
2790 ObjCInterfaceDecl *OI = OIT->getDecl();
2791 S += '"';
2792 S += OI->getNameAsCString();
2793 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2794 E = OIT->qual_end(); I != E; ++I) {
2795 S += '<';
2796 S += (*I)->getNameAsString();
2797 S += '>';
2798 }
2799 S += '"';
2800 }
2801 return;
2802 }
2803
2804 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002805}
2806
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002807void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002808 std::string& S) const {
2809 if (QT & Decl::OBJC_TQ_In)
2810 S += 'n';
2811 if (QT & Decl::OBJC_TQ_Inout)
2812 S += 'N';
2813 if (QT & Decl::OBJC_TQ_Out)
2814 S += 'o';
2815 if (QT & Decl::OBJC_TQ_Bycopy)
2816 S += 'O';
2817 if (QT & Decl::OBJC_TQ_Byref)
2818 S += 'R';
2819 if (QT & Decl::OBJC_TQ_Oneway)
2820 S += 'V';
2821}
2822
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002823void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002824 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2825
2826 BuiltinVaListType = T;
2827}
2828
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002829void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002830 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00002831}
2832
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002833void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00002834 ObjCSelType = T;
2835
2836 const TypedefType *TT = T->getAsTypedefType();
2837 if (!TT)
2838 return;
2839 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002840
2841 // typedef struct objc_selector *SEL;
Ted Kremenek35366a62009-07-17 17:50:17 +00002842 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002843 if (!ptr)
2844 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002845 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002846 if (!rec)
2847 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002848 SelStructType = rec;
2849}
2850
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002851void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002852 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002853}
2854
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002855void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002856 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00002857}
2858
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2860 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002861 "'NSConstantString' type already set!");
2862
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002863 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002864}
2865
Douglas Gregor7532dc62009-03-30 22:58:21 +00002866/// \brief Retrieve the template name that represents a qualified
2867/// template name such as \c std::vector.
2868TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2869 bool TemplateKeyword,
2870 TemplateDecl *Template) {
2871 llvm::FoldingSetNodeID ID;
2872 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2873
2874 void *InsertPos = 0;
2875 QualifiedTemplateName *QTN =
2876 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2877 if (!QTN) {
2878 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2879 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2880 }
2881
2882 return TemplateName(QTN);
2883}
2884
2885/// \brief Retrieve the template name that represents a dependent
2886/// template name such as \c MetaFun::template apply.
2887TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2888 const IdentifierInfo *Name) {
2889 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2890
2891 llvm::FoldingSetNodeID ID;
2892 DependentTemplateName::Profile(ID, NNS, Name);
2893
2894 void *InsertPos = 0;
2895 DependentTemplateName *QTN =
2896 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2897
2898 if (QTN)
2899 return TemplateName(QTN);
2900
2901 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2902 if (CanonNNS == NNS) {
2903 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2904 } else {
2905 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2906 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2907 }
2908
2909 DependentTemplateNames.InsertNode(QTN, InsertPos);
2910 return TemplateName(QTN);
2911}
2912
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002913/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002914/// TargetInfo, produce the corresponding type. The unsigned @p Type
2915/// is actually a value of type @c TargetInfo::IntType.
2916QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002917 switch (Type) {
2918 case TargetInfo::NoInt: return QualType();
2919 case TargetInfo::SignedShort: return ShortTy;
2920 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2921 case TargetInfo::SignedInt: return IntTy;
2922 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2923 case TargetInfo::SignedLong: return LongTy;
2924 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2925 case TargetInfo::SignedLongLong: return LongLongTy;
2926 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2927 }
2928
2929 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002930 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002931}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002932
2933//===----------------------------------------------------------------------===//
2934// Type Predicates.
2935//===----------------------------------------------------------------------===//
2936
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002937/// isObjCNSObjectType - Return true if this is an NSObject object using
2938/// NSObject attribute on a c-style pointer type.
2939/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00002940/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002941///
2942bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2943 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2944 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002945 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002946 return true;
2947 }
2948 return false;
2949}
2950
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002951/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2952/// garbage collection attribute.
2953///
2954QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002955 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002956 if (getLangOptions().ObjC1 &&
2957 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002958 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002959 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002960 // (or pointers to them) be treated as though they were declared
2961 // as __strong.
2962 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00002963 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002964 GCAttrs = QualType::Strong;
2965 else if (Ty->isPointerType())
Ted Kremenek35366a62009-07-17 17:50:17 +00002966 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002967 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002968 // Non-pointers have none gc'able attribute regardless of the attribute
2969 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00002970 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002971 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002972 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002973 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002974}
2975
Chris Lattner6ac46a42008-04-07 06:51:04 +00002976//===----------------------------------------------------------------------===//
2977// Type Compatibility Testing
2978//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002979
Chris Lattner6ac46a42008-04-07 06:51:04 +00002980/// areCompatVectorTypes - Return true if the two specified vector types are
2981/// compatible.
2982static bool areCompatVectorTypes(const VectorType *LHS,
2983 const VectorType *RHS) {
2984 assert(LHS->isCanonical() && RHS->isCanonical());
2985 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002986 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002987}
2988
Eli Friedman3d815e72008-08-22 00:56:42 +00002989/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002990/// compatible for assignment from RHS to LHS. This handles validation of any
2991/// protocol qualifiers on the LHS or RHS.
2992///
Steve Naroff14108da2009-07-10 23:34:53 +00002993/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
2994bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2995 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002996 // If either type represents the built-in 'id' or 'Class' types, return true.
2997 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002998 return true;
2999
3000 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3001 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroffde2e22d2009-07-15 18:40:39 +00003002 if (!LHS || !RHS) {
3003 // We have qualified builtin types.
3004 // Both the right and left sides have qualifiers.
3005 for (ObjCObjectPointerType::qual_iterator I = LHSOPT->qual_begin(),
3006 E = LHSOPT->qual_end(); I != E; ++I) {
3007 bool RHSImplementsProtocol = false;
3008
3009 // when comparing an id<P> on lhs with a static type on rhs,
3010 // see if static class implements all of id's protocols, directly or
3011 // through its super class and categories.
3012 for (ObjCObjectPointerType::qual_iterator J = RHSOPT->qual_begin(),
3013 E = RHSOPT->qual_end(); J != E; ++J) {
Steve Naroff8f167562009-07-16 16:21:02 +00003014 if ((*J)->lookupProtocolNamed((*I)->getIdentifier())) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003015 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003016 break;
3017 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003018 }
3019 if (!RHSImplementsProtocol)
3020 return false;
3021 }
3022 // The RHS implements all protocols listed on the LHS.
3023 return true;
3024 }
Steve Naroff14108da2009-07-10 23:34:53 +00003025 return canAssignObjCInterfaces(LHS, RHS);
3026}
3027
Eli Friedman3d815e72008-08-22 00:56:42 +00003028bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3029 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003030 // Verify that the base decls are compatible: the RHS must be a subclass of
3031 // the LHS.
3032 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3033 return false;
3034
3035 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3036 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003037 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003038 return true;
3039
3040 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3041 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003042 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003043 return true; // FIXME: should return false!
3044
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003045 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3046 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003047 LHSPI != LHSPE; LHSPI++) {
3048 bool RHSImplementsProtocol = false;
3049
3050 // If the RHS doesn't implement the protocol on the left, the types
3051 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003052 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3053 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003054 RHSPI != RHSPE; RHSPI++) {
3055 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003056 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003057 break;
3058 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003059 }
3060 // FIXME: For better diagnostics, consider passing back the protocol name.
3061 if (!RHSImplementsProtocol)
3062 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003063 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003064 // The RHS implements all protocols listed on the LHS.
3065 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003066}
3067
Steve Naroff389bf462009-02-12 17:52:19 +00003068bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3069 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003070 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3071 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003072
Steve Naroff14108da2009-07-10 23:34:53 +00003073 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003074 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003075
3076 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3077 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003078}
3079
Steve Naroffec0550f2007-10-15 20:41:53 +00003080/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3081/// both shall have the identically qualified version of a compatible type.
3082/// C99 6.2.7p1: Two types have compatible types if their types are the
3083/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003084bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3085 return !mergeTypes(LHS, RHS).isNull();
3086}
3087
3088QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3089 const FunctionType *lbase = lhs->getAsFunctionType();
3090 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003091 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3092 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003093 bool allLTypes = true;
3094 bool allRTypes = true;
3095
3096 // Check return type
3097 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3098 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003099 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3100 allLTypes = false;
3101 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3102 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003103
3104 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003105 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3106 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003107 unsigned lproto_nargs = lproto->getNumArgs();
3108 unsigned rproto_nargs = rproto->getNumArgs();
3109
3110 // Compatible functions must have the same number of arguments
3111 if (lproto_nargs != rproto_nargs)
3112 return QualType();
3113
3114 // Variadic and non-variadic functions aren't compatible
3115 if (lproto->isVariadic() != rproto->isVariadic())
3116 return QualType();
3117
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003118 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3119 return QualType();
3120
Eli Friedman3d815e72008-08-22 00:56:42 +00003121 // Check argument compatibility
3122 llvm::SmallVector<QualType, 10> types;
3123 for (unsigned i = 0; i < lproto_nargs; i++) {
3124 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3125 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3126 QualType argtype = mergeTypes(largtype, rargtype);
3127 if (argtype.isNull()) return QualType();
3128 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003129 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3130 allLTypes = false;
3131 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3132 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003133 }
3134 if (allLTypes) return lhs;
3135 if (allRTypes) return rhs;
3136 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003137 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003138 }
3139
3140 if (lproto) allRTypes = false;
3141 if (rproto) allLTypes = false;
3142
Douglas Gregor72564e72009-02-26 23:50:07 +00003143 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003144 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003145 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003146 if (proto->isVariadic()) return QualType();
3147 // Check that the types are compatible with the types that
3148 // would result from default argument promotions (C99 6.7.5.3p15).
3149 // The only types actually affected are promotable integer
3150 // types and floats, which would be passed as a different
3151 // type depending on whether the prototype is visible.
3152 unsigned proto_nargs = proto->getNumArgs();
3153 for (unsigned i = 0; i < proto_nargs; ++i) {
3154 QualType argTy = proto->getArgType(i);
3155 if (argTy->isPromotableIntegerType() ||
3156 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3157 return QualType();
3158 }
3159
3160 if (allLTypes) return lhs;
3161 if (allRTypes) return rhs;
3162 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003163 proto->getNumArgs(), lproto->isVariadic(),
3164 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003165 }
3166
3167 if (allLTypes) return lhs;
3168 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003169 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003170}
3171
3172QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003173 // C++ [expr]: If an expression initially has the type "reference to T", the
3174 // type is adjusted to "T" prior to any further analysis, the expression
3175 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003176 // expression is an lvalue unless the reference is an rvalue reference and
3177 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003178 // FIXME: C++ shouldn't be going through here! The rules are different
3179 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003180 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3181 // shouldn't be going through here!
Ted Kremenek35366a62009-07-17 17:50:17 +00003182 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003183 LHS = RT->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00003184 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003185 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003186
Eli Friedman3d815e72008-08-22 00:56:42 +00003187 QualType LHSCan = getCanonicalType(LHS),
3188 RHSCan = getCanonicalType(RHS);
3189
3190 // If two types are identical, they are compatible.
3191 if (LHSCan == RHSCan)
3192 return LHS;
3193
3194 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003195 // Note that we handle extended qualifiers later, in the
3196 // case for ExtQualType.
3197 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003198 return QualType();
3199
Eli Friedman852d63b2009-06-01 01:22:52 +00003200 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3201 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003202
Chris Lattner1adb8832008-01-14 05:45:46 +00003203 // We want to consider the two function types to be the same for these
3204 // comparisons, just force one to the other.
3205 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3206 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003207
Eli Friedman07d25872009-06-02 05:28:56 +00003208 // Strip off objc_gc attributes off the top level so they can be merged.
3209 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003210 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003211 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3212 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003213 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003214 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003215 // __strong attribue is redundant if other decl is an objective-c
3216 // object pointer (or decorated with __strong attribute); otherwise
3217 // issue error.
3218 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3219 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003220 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003221 return QualType();
3222
Eli Friedman07d25872009-06-02 05:28:56 +00003223 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3224 RHS.getCVRQualifiers());
3225 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003226 if (!Result.isNull()) {
3227 if (Result.getObjCGCAttr() == QualType::GCNone)
3228 Result = getObjCGCQualType(Result, GCAttr);
3229 else if (Result.getObjCGCAttr() != GCAttr)
3230 Result = QualType();
3231 }
Eli Friedman07d25872009-06-02 05:28:56 +00003232 return Result;
3233 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003234 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003235 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003236 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3237 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003238 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3239 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003240 // __strong attribue is redundant if other decl is an objective-c
3241 // object pointer (or decorated with __strong attribute); otherwise
3242 // issue error.
3243 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3244 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003245 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003246 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003247
Eli Friedman07d25872009-06-02 05:28:56 +00003248 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3249 LHS.getCVRQualifiers());
3250 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003251 if (!Result.isNull()) {
3252 if (Result.getObjCGCAttr() == QualType::GCNone)
3253 Result = getObjCGCQualType(Result, GCAttr);
3254 else if (Result.getObjCGCAttr() != GCAttr)
3255 Result = QualType();
3256 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003257 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003258 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003259 }
3260
Eli Friedman4c721d32008-02-12 08:23:06 +00003261 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003262 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3263 LHSClass = Type::ConstantArray;
3264 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3265 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003266
Nate Begeman213541a2008-04-18 23:10:10 +00003267 // Canonicalize ExtVector -> Vector.
3268 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3269 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003270
3271 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003272 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003273 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3274 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003275 if (const EnumType* ETy = LHS->getAsEnumType()) {
3276 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3277 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003278 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003279 if (const EnumType* ETy = RHS->getAsEnumType()) {
3280 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3281 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003282 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003283
Eli Friedman3d815e72008-08-22 00:56:42 +00003284 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003285 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003286
Steve Naroff4a746782008-01-09 22:43:08 +00003287 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003288 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003289#define TYPE(Class, Base)
3290#define ABSTRACT_TYPE(Class, Base)
3291#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3292#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3293#include "clang/AST/TypeNodes.def"
3294 assert(false && "Non-canonical and dependent types shouldn't get here");
3295 return QualType();
3296
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003297 case Type::LValueReference:
3298 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003299 case Type::MemberPointer:
3300 assert(false && "C++ should never be in mergeTypes");
3301 return QualType();
3302
3303 case Type::IncompleteArray:
3304 case Type::VariableArray:
3305 case Type::FunctionProto:
3306 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003307 assert(false && "Types are eliminated above");
3308 return QualType();
3309
Chris Lattner1adb8832008-01-14 05:45:46 +00003310 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003311 {
3312 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003313 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3314 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003315 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3316 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003317 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003318 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003319 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003320 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003321 return getPointerType(ResultType);
3322 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003323 case Type::BlockPointer:
3324 {
3325 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003326 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3327 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003328 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3329 if (ResultType.isNull()) return QualType();
3330 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3331 return LHS;
3332 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3333 return RHS;
3334 return getBlockPointerType(ResultType);
3335 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003336 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003337 {
3338 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3339 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3340 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3341 return QualType();
3342
3343 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3344 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3345 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3346 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003347 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3348 return LHS;
3349 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3350 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003351 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3352 ArrayType::ArraySizeModifier(), 0);
3353 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3354 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003355 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3356 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003357 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3358 return LHS;
3359 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3360 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003361 if (LVAT) {
3362 // FIXME: This isn't correct! But tricky to implement because
3363 // the array's size has to be the size of LHS, but the type
3364 // has to be different.
3365 return LHS;
3366 }
3367 if (RVAT) {
3368 // FIXME: This isn't correct! But tricky to implement because
3369 // the array's size has to be the size of RHS, but the type
3370 // has to be different.
3371 return RHS;
3372 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003373 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3374 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003375 return getIncompleteArrayType(ResultType,
3376 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003377 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003378 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003379 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003380 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003381 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003382 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003383 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003384 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003385 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003386 case Type::Complex:
3387 // Distinct complex types are incompatible.
3388 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003389 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003390 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003391 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3392 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003393 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003394 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003395 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003396 // FIXME: This should be type compatibility, e.g. whether
3397 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003398 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3399 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3400 if (LHSIface && RHSIface &&
3401 canAssignObjCInterfaces(LHSIface, RHSIface))
3402 return LHS;
3403
Eli Friedman3d815e72008-08-22 00:56:42 +00003404 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003405 }
Steve Naroff14108da2009-07-10 23:34:53 +00003406 case Type::ObjCObjectPointer: {
3407 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3408 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3409 return QualType();
3410
3411 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3412 RHS->getAsObjCObjectPointerType()))
3413 return LHS;
3414
Steve Naroffbc76dd02008-12-10 22:14:21 +00003415 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003416 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003417 case Type::FixedWidthInt:
3418 // Distinct fixed-width integers are not compatible.
3419 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003420 case Type::ExtQual:
3421 // FIXME: ExtQual types can be compatible even if they're not
3422 // identical!
3423 return QualType();
3424 // First attempt at an implementation, but I'm not really sure it's
3425 // right...
3426#if 0
3427 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3428 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3429 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3430 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3431 return QualType();
3432 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3433 LHSBase = QualType(LQual->getBaseType(), 0);
3434 RHSBase = QualType(RQual->getBaseType(), 0);
3435 ResultType = mergeTypes(LHSBase, RHSBase);
3436 if (ResultType.isNull()) return QualType();
3437 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3438 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3439 return LHS;
3440 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3441 return RHS;
3442 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3443 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3444 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3445 return ResultType;
3446#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003447
3448 case Type::TemplateSpecialization:
3449 assert(false && "Dependent types have no size");
3450 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003451 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003452
3453 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003454}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003455
Chris Lattner5426bf62008-04-07 07:01:58 +00003456//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003457// Integer Predicates
3458//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003459
Eli Friedmanad74a752008-06-28 06:23:08 +00003460unsigned ASTContext::getIntWidth(QualType T) {
3461 if (T == BoolTy)
3462 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003463 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3464 return FWIT->getWidth();
3465 }
3466 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003467 return (unsigned)getTypeSize(T);
3468}
3469
3470QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3471 assert(T->isSignedIntegerType() && "Unexpected type");
3472 if (const EnumType* ETy = T->getAsEnumType())
3473 T = ETy->getDecl()->getIntegerType();
3474 const BuiltinType* BTy = T->getAsBuiltinType();
3475 assert (BTy && "Unexpected signed integer type");
3476 switch (BTy->getKind()) {
3477 case BuiltinType::Char_S:
3478 case BuiltinType::SChar:
3479 return UnsignedCharTy;
3480 case BuiltinType::Short:
3481 return UnsignedShortTy;
3482 case BuiltinType::Int:
3483 return UnsignedIntTy;
3484 case BuiltinType::Long:
3485 return UnsignedLongTy;
3486 case BuiltinType::LongLong:
3487 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003488 case BuiltinType::Int128:
3489 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003490 default:
3491 assert(0 && "Unexpected signed integer type");
3492 return QualType();
3493 }
3494}
3495
Douglas Gregor2cf26342009-04-09 22:27:44 +00003496ExternalASTSource::~ExternalASTSource() { }
3497
3498void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003499
3500
3501//===----------------------------------------------------------------------===//
3502// Builtin Type Computation
3503//===----------------------------------------------------------------------===//
3504
3505/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3506/// pointer over the consumed characters. This returns the resultant type.
3507static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3508 ASTContext::GetBuiltinTypeError &Error,
3509 bool AllowTypeModifiers = true) {
3510 // Modifiers.
3511 int HowLong = 0;
3512 bool Signed = false, Unsigned = false;
3513
3514 // Read the modifiers first.
3515 bool Done = false;
3516 while (!Done) {
3517 switch (*Str++) {
3518 default: Done = true; --Str; break;
3519 case 'S':
3520 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3521 assert(!Signed && "Can't use 'S' modifier multiple times!");
3522 Signed = true;
3523 break;
3524 case 'U':
3525 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3526 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3527 Unsigned = true;
3528 break;
3529 case 'L':
3530 assert(HowLong <= 2 && "Can't have LLLL modifier");
3531 ++HowLong;
3532 break;
3533 }
3534 }
3535
3536 QualType Type;
3537
3538 // Read the base type.
3539 switch (*Str++) {
3540 default: assert(0 && "Unknown builtin type letter!");
3541 case 'v':
3542 assert(HowLong == 0 && !Signed && !Unsigned &&
3543 "Bad modifiers used with 'v'!");
3544 Type = Context.VoidTy;
3545 break;
3546 case 'f':
3547 assert(HowLong == 0 && !Signed && !Unsigned &&
3548 "Bad modifiers used with 'f'!");
3549 Type = Context.FloatTy;
3550 break;
3551 case 'd':
3552 assert(HowLong < 2 && !Signed && !Unsigned &&
3553 "Bad modifiers used with 'd'!");
3554 if (HowLong)
3555 Type = Context.LongDoubleTy;
3556 else
3557 Type = Context.DoubleTy;
3558 break;
3559 case 's':
3560 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3561 if (Unsigned)
3562 Type = Context.UnsignedShortTy;
3563 else
3564 Type = Context.ShortTy;
3565 break;
3566 case 'i':
3567 if (HowLong == 3)
3568 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3569 else if (HowLong == 2)
3570 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3571 else if (HowLong == 1)
3572 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3573 else
3574 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3575 break;
3576 case 'c':
3577 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3578 if (Signed)
3579 Type = Context.SignedCharTy;
3580 else if (Unsigned)
3581 Type = Context.UnsignedCharTy;
3582 else
3583 Type = Context.CharTy;
3584 break;
3585 case 'b': // boolean
3586 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3587 Type = Context.BoolTy;
3588 break;
3589 case 'z': // size_t.
3590 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3591 Type = Context.getSizeType();
3592 break;
3593 case 'F':
3594 Type = Context.getCFConstantStringType();
3595 break;
3596 case 'a':
3597 Type = Context.getBuiltinVaListType();
3598 assert(!Type.isNull() && "builtin va list type not initialized!");
3599 break;
3600 case 'A':
3601 // This is a "reference" to a va_list; however, what exactly
3602 // this means depends on how va_list is defined. There are two
3603 // different kinds of va_list: ones passed by value, and ones
3604 // passed by reference. An example of a by-value va_list is
3605 // x86, where va_list is a char*. An example of by-ref va_list
3606 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3607 // we want this argument to be a char*&; for x86-64, we want
3608 // it to be a __va_list_tag*.
3609 Type = Context.getBuiltinVaListType();
3610 assert(!Type.isNull() && "builtin va list type not initialized!");
3611 if (Type->isArrayType()) {
3612 Type = Context.getArrayDecayedType(Type);
3613 } else {
3614 Type = Context.getLValueReferenceType(Type);
3615 }
3616 break;
3617 case 'V': {
3618 char *End;
3619
3620 unsigned NumElements = strtoul(Str, &End, 10);
3621 assert(End != Str && "Missing vector size");
3622
3623 Str = End;
3624
3625 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3626 Type = Context.getVectorType(ElementType, NumElements);
3627 break;
3628 }
3629 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003630 Type = Context.getFILEType();
3631 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003632 Error = ASTContext::GE_Missing_FILE;
3633 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003634 } else {
3635 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003636 }
3637 }
3638 }
3639
3640 if (!AllowTypeModifiers)
3641 return Type;
3642
3643 Done = false;
3644 while (!Done) {
3645 switch (*Str++) {
3646 default: Done = true; --Str; break;
3647 case '*':
3648 Type = Context.getPointerType(Type);
3649 break;
3650 case '&':
3651 Type = Context.getLValueReferenceType(Type);
3652 break;
3653 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3654 case 'C':
3655 Type = Type.getQualifiedType(QualType::Const);
3656 break;
3657 }
3658 }
3659
3660 return Type;
3661}
3662
3663/// GetBuiltinType - Return the type for the specified builtin.
3664QualType ASTContext::GetBuiltinType(unsigned id,
3665 GetBuiltinTypeError &Error) {
3666 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3667
3668 llvm::SmallVector<QualType, 8> ArgTypes;
3669
3670 Error = GE_None;
3671 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3672 if (Error != GE_None)
3673 return QualType();
3674 while (TypeStr[0] && TypeStr[0] != '.') {
3675 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3676 if (Error != GE_None)
3677 return QualType();
3678
3679 // Do array -> pointer decay. The builtin should use the decayed type.
3680 if (Ty->isArrayType())
3681 Ty = getArrayDecayedType(Ty);
3682
3683 ArgTypes.push_back(Ty);
3684 }
3685
3686 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3687 "'.' should only occur at end of builtin type list!");
3688
3689 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3690 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3691 return getFunctionNoProtoType(ResType);
3692 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3693 TypeStr[0] == '.', 0);
3694}