blob: 4684a806f05e7785446bf38eabe53576e14e1926 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff3fafa102007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Anders Carlsson63f1ad92009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnerb09b31d2009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman7903d052009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerf4fbc442009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson5d382582009-07-18 21:19:52 +000027#include "RecordLayoutBuilder.h"
28
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
31enum FloatingRank {
32 FloatRank, DoubleRank, LongDoubleRank
33};
34
Chris Lattner2fda0ed2008-10-05 17:34:18 +000035ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
36 TargetInfo &t,
Daniel Dunbarde300732008-08-11 04:54:23 +000037 IdentifierTable &idents, SelectorTable &sels,
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000038 Builtin::Context &builtins,
39 bool FreeMem, unsigned size_reserve) :
Douglas Gregor1e589cc2009-03-26 23:50:42 +000040 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Douglas Gregor151fac72009-07-07 16:35:42 +000041 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
42 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregora252b232009-07-02 17:08:52 +000043 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
44 Idents(idents), Selectors(sels),
Chris Lattner7099c782009-06-30 01:26:17 +000045 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbarde300732008-08-11 04:54:23 +000046 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbarde300732008-08-11 04:54:23 +000047 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff329ec222009-07-10 23:34:53 +000048 InitBuiltinTypes();
Daniel Dunbarde300732008-08-11 04:54:23 +000049}
50
Chris Lattner4b009652007-07-25 00:24:17 +000051ASTContext::~ASTContext() {
52 // Deallocate all the types.
53 while (!Types.empty()) {
Ted Kremenekdb4d5972008-05-21 16:38:54 +000054 Types.back()->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000055 Types.pop_back();
56 }
Eli Friedman65489b72008-05-27 03:08:09 +000057
Nuno Lopes355a8682008-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 Dunbar1fbaef12009-05-03 10:38:35 +000068 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
69 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopes355a8682008-12-17 22:30:25 +000070 while (I != E) {
71 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
72 delete R;
73 }
74 }
75
Douglas Gregor1e589cc2009-03-26 23:50:42 +000076 // Destroy nested-name-specifiers.
Douglas Gregor3c4eae52009-03-27 23:54:10 +000077 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
78 NNS = NestedNameSpecifiers.begin(),
79 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregorbccd97c2009-03-27 23:25:45 +000080 NNS != NNSEnd;
Douglas Gregor3c4eae52009-03-27 23:54:10 +000081 /* Increment in loop */)
82 (*NNS++).Destroy(*this);
Douglas Gregor1e589cc2009-03-26 23:50:42 +000083
84 if (GlobalNestedNameSpecifier)
85 GlobalNestedNameSpecifier->Destroy(*this);
86
Eli Friedman65489b72008-05-27 03:08:09 +000087 TUDecl->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000088}
89
Douglas Gregorc34897d2009-04-09 22:27:44 +000090void
91ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
92 ExternalSource.reset(Source.take());
93}
94
Chris Lattner4b009652007-07-25 00:24:17 +000095void ASTContext::PrintStats() const {
96 fprintf(stderr, "*** AST Context Stats:\n");
97 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redlce6fff02009-03-16 23:22:08 +000098
Douglas Gregore6609442009-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 Gregord2b6edc2009-04-07 17:20:56 +0000105
Chris Lattner4b009652007-07-25 00:24:17 +0000106 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
107 Type *T = Types[i];
Douglas Gregore6609442009-05-26 14:40:08 +0000108 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4b009652007-07-25 00:24:17 +0000109 }
110
Douglas Gregore6609442009-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 Gregorc34897d2009-04-09 22:27:44 +0000122
123 if (ExternalSource.get()) {
124 fprintf(stderr, "\n");
125 ExternalSource->PrintStats();
126 }
Chris Lattner4b009652007-07-25 00:24:17 +0000127}
128
129
130void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Naroff93fd2112009-01-27 22:08:43 +0000131 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +0000132}
133
Chris Lattner4b009652007-07-25 00:24:17 +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 Friedmand9389be2009-06-05 07:05:05 +0000143 if (LangOpts.CharIsSigned)
Chris Lattner4b009652007-07-25 00:24:17 +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);
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000165
Chris Lattner6cc7e412009-04-30 02:43:43 +0000166 // GNU extension, 128-bit integers.
167 InitBuiltinType(Int128Ty, BuiltinType::Int128);
168 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
169
Chris Lattnere1dafe72009-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());
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000174
Alisdair Meredith2bcacb62009-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 Gregord2baafd2008-10-21 16:13:35 +0000185 // Placeholder type for functions.
Douglas Gregor1b21c7f2008-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 Gregord2baafd2008-10-21 16:13:35 +0000194
Anders Carlsson4a8498c2009-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
Chris Lattner4b009652007-07-25 00:24:17 +0000199 // C99 6.2.5p11.
200 FloatComplexTy = getComplexType(FloatTy);
201 DoubleComplexTy = getComplexType(DoubleTy);
202 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000203
Steve Naroff9d12c902007-10-15 14:41:52 +0000204 BuiltinVaListType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000205
Steve Naroff7bffd372009-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 Naroff329ec222009-07-10 23:34:53 +0000213
Ted Kremenek42730c52008-01-07 19:49:32 +0000214 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000215
216 // void * type
217 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000218
219 // nullptr type (C++0x 2.14.7)
220 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner4b009652007-07-25 00:24:17 +0000221}
222
Douglas Gregor181fe792009-07-24 20:34:43 +0000223VarDecl *ASTContext::getInstantiatedFromStaticDataMember(VarDecl *Var) {
224 assert(Var->isStaticDataMember() && "Not a static data member");
225 llvm::DenseMap<VarDecl *, VarDecl *>::iterator Pos
226 = InstantiatedFromStaticDataMember.find(Var);
227 if (Pos == InstantiatedFromStaticDataMember.end())
228 return 0;
229
230 return Pos->second;
231}
232
233void
234ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) {
235 assert(Inst->isStaticDataMember() && "Not a static data member");
236 assert(Tmpl->isStaticDataMember() && "Not a static data member");
237 assert(!InstantiatedFromStaticDataMember[Inst] &&
238 "Already noted what static data member was instantiated from");
239 InstantiatedFromStaticDataMember[Inst] = Tmpl;
240}
241
Douglas Gregora252b232009-07-02 17:08:52 +0000242namespace {
243 class BeforeInTranslationUnit
244 : std::binary_function<SourceRange, SourceRange, bool> {
245 SourceManager *SourceMgr;
246
247 public:
248 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
249
250 bool operator()(SourceRange X, SourceRange Y) {
251 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
252 }
253 };
254}
255
256/// \brief Determine whether the given comment is a Doxygen-style comment.
257///
258/// \param Start the start of the comment text.
259///
260/// \param End the end of the comment text.
261///
262/// \param Member whether we want to check whether this is a member comment
263/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
264/// we only return true when we find a non-member comment.
265static bool
266isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
267 bool Member = false) {
268 const char *BufferStart
269 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
270 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
271 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
272
273 if (End - Start < 4)
274 return false;
275
276 assert(Start[0] == '/' && "Not a comment?");
277 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
278 return false;
279 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
280 return false;
281
282 return (Start[3] == '<') == Member;
283}
284
285/// \brief Retrieve the comment associated with the given declaration, if
286/// it has one.
287const char *ASTContext::getCommentForDecl(const Decl *D) {
288 if (!D)
289 return 0;
290
291 // Check whether we have cached a comment string for this declaration
292 // already.
293 llvm::DenseMap<const Decl *, std::string>::iterator Pos
294 = DeclComments.find(D);
295 if (Pos != DeclComments.end())
296 return Pos->second.c_str();
297
298 // If we have an external AST source and have not yet loaded comments from
299 // that source, do so now.
300 if (ExternalSource && !LoadedExternalComments) {
301 std::vector<SourceRange> LoadedComments;
302 ExternalSource->ReadComments(LoadedComments);
303
304 if (!LoadedComments.empty())
305 Comments.insert(Comments.begin(), LoadedComments.begin(),
306 LoadedComments.end());
307
308 LoadedExternalComments = true;
309 }
310
311 // If there are no comments anywhere, we won't find anything.
312 if (Comments.empty())
313 return 0;
314
315 // If the declaration doesn't map directly to a location in a file, we
316 // can't find the comment.
317 SourceLocation DeclStartLoc = D->getLocStart();
318 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
319 return 0;
320
321 // Find the comment that occurs just before this declaration.
322 std::vector<SourceRange>::iterator LastComment
323 = std::lower_bound(Comments.begin(), Comments.end(),
324 SourceRange(DeclStartLoc),
325 BeforeInTranslationUnit(&SourceMgr));
326
327 // Decompose the location for the start of the declaration and find the
328 // beginning of the file buffer.
329 std::pair<FileID, unsigned> DeclStartDecomp
330 = SourceMgr.getDecomposedLoc(DeclStartLoc);
331 const char *FileBufferStart
332 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
333
334 // First check whether we have a comment for a member.
335 if (LastComment != Comments.end() &&
336 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
337 isDoxygenComment(SourceMgr, *LastComment, true)) {
338 std::pair<FileID, unsigned> LastCommentEndDecomp
339 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
340 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
341 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
342 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
343 LastCommentEndDecomp.second)) {
344 // The Doxygen member comment comes after the declaration starts and
345 // is on the same line and in the same file as the declaration. This
346 // is the comment we want.
347 std::string &Result = DeclComments[D];
348 Result.append(FileBufferStart +
349 SourceMgr.getFileOffset(LastComment->getBegin()),
350 FileBufferStart + LastCommentEndDecomp.second + 1);
351 return Result.c_str();
352 }
353 }
354
355 if (LastComment == Comments.begin())
356 return 0;
357 --LastComment;
358
359 // Decompose the end of the comment.
360 std::pair<FileID, unsigned> LastCommentEndDecomp
361 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
362
363 // If the comment and the declaration aren't in the same file, then they
364 // aren't related.
365 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
366 return 0;
367
368 // Check that we actually have a Doxygen comment.
369 if (!isDoxygenComment(SourceMgr, *LastComment))
370 return 0;
371
372 // Compute the starting line for the declaration and for the end of the
373 // comment (this is expensive).
374 unsigned DeclStartLine
375 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
376 unsigned CommentEndLine
377 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
378 LastCommentEndDecomp.second);
379
380 // If the comment does not end on the line prior to the declaration, then
381 // the comment is not associated with the declaration at all.
382 if (CommentEndLine + 1 != DeclStartLine)
383 return 0;
384
385 // We have a comment, but there may be more comments on the previous lines.
386 // Keep looking so long as the comments are still Doxygen comments and are
387 // still adjacent.
388 unsigned ExpectedLine
389 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
390 std::vector<SourceRange>::iterator FirstComment = LastComment;
391 while (FirstComment != Comments.begin()) {
392 // Look at the previous comment
393 --FirstComment;
394 std::pair<FileID, unsigned> Decomp
395 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
396
397 // If this previous comment is in a different file, we're done.
398 if (Decomp.first != DeclStartDecomp.first) {
399 ++FirstComment;
400 break;
401 }
402
403 // If this comment is not a Doxygen comment, we're done.
404 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
405 ++FirstComment;
406 break;
407 }
408
409 // If the line number is not what we expected, we're done.
410 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
411 if (Line != ExpectedLine) {
412 ++FirstComment;
413 break;
414 }
415
416 // Set the next expected line number.
417 ExpectedLine
418 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
419 }
420
421 // The iterator range [FirstComment, LastComment] contains all of the
422 // BCPL comments that, together, are associated with this declaration.
423 // Form a single comment block string for this declaration that concatenates
424 // all of these comments.
425 std::string &Result = DeclComments[D];
426 while (FirstComment != LastComment) {
427 std::pair<FileID, unsigned> DecompStart
428 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
429 std::pair<FileID, unsigned> DecompEnd
430 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
431 Result.append(FileBufferStart + DecompStart.second,
432 FileBufferStart + DecompEnd.second + 1);
433 ++FirstComment;
434 }
435
436 // Append the last comment line.
437 Result.append(FileBufferStart +
438 SourceMgr.getFileOffset(LastComment->getBegin()),
439 FileBufferStart + LastCommentEndDecomp.second + 1);
440 return Result.c_str();
441}
442
Chris Lattner4b009652007-07-25 00:24:17 +0000443//===----------------------------------------------------------------------===//
444// Type Sizing and Analysis
445//===----------------------------------------------------------------------===//
446
Chris Lattner2a674dc2008-06-30 18:32:54 +0000447/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
448/// scalar floating point type.
449const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
450 const BuiltinType *BT = T->getAsBuiltinType();
451 assert(BT && "Not a floating point type!");
452 switch (BT->getKind()) {
453 default: assert(0 && "Not a floating point type!");
454 case BuiltinType::Float: return Target.getFloatFormat();
455 case BuiltinType::Double: return Target.getDoubleFormat();
456 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
457 }
458}
459
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000460/// getDeclAlign - Return a conservative estimate of the alignment of the
461/// specified decl. Note that bitfields do not have a valid alignment, so
462/// this method will assert on them.
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000463unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedman0ee57322009-02-22 02:56:25 +0000464 unsigned Align = Target.getCharWidth();
465
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000466 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedman0ee57322009-02-22 02:56:25 +0000467 Align = std::max(Align, AA->getAlignment());
468
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000469 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
470 QualType T = VD->getType();
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000471 if (const ReferenceType* RT = T->getAsReferenceType()) {
Anders Carlssonaa0783b2009-04-10 04:47:03 +0000472 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssoneeaeda32009-04-10 04:52:36 +0000473 Align = Target.getPointerAlign(AS);
Anders Carlssonaa0783b2009-04-10 04:47:03 +0000474 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
475 // Incomplete or function types default to 1.
Eli Friedman0ee57322009-02-22 02:56:25 +0000476 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
477 T = cast<ArrayType>(T)->getElementType();
478
479 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
480 }
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000481 }
Eli Friedman0ee57322009-02-22 02:56:25 +0000482
483 return Align / Target.getCharWidth();
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000484}
Chris Lattner2a674dc2008-06-30 18:32:54 +0000485
Chris Lattner4b009652007-07-25 00:24:17 +0000486/// getTypeSize - Return the size of the specified type, in bits. This method
487/// does not work on incomplete types.
488std::pair<uint64_t, unsigned>
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000489ASTContext::getTypeInfo(const Type *T) {
Mike Stump44d1f402009-02-27 18:32:39 +0000490 uint64_t Width=0;
491 unsigned Align=8;
Chris Lattner4b009652007-07-25 00:24:17 +0000492 switch (T->getTypeClass()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000493#define TYPE(Class, Base)
494#define ABSTRACT_TYPE(Class, Base)
Douglas Gregorab380272009-04-30 17:32:17 +0000495#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor4fa58902009-02-26 23:50:07 +0000496#define DEPENDENT_TYPE(Class, Base) case Type::Class:
497#include "clang/AST/TypeNodes.def"
Douglas Gregorab380272009-04-30 17:32:17 +0000498 assert(false && "Should not see dependent types");
Douglas Gregor4fa58902009-02-26 23:50:07 +0000499 break;
500
Chris Lattner4b009652007-07-25 00:24:17 +0000501 case Type::FunctionNoProto:
502 case Type::FunctionProto:
Douglas Gregorab380272009-04-30 17:32:17 +0000503 // GCC extension: alignof(function) = 32 bits
504 Width = 0;
505 Align = 32;
506 break;
507
Douglas Gregor4fa58902009-02-26 23:50:07 +0000508 case Type::IncompleteArray:
Steve Naroff83c13012007-08-30 01:06:46 +0000509 case Type::VariableArray:
Douglas Gregorab380272009-04-30 17:32:17 +0000510 Width = 0;
511 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
512 break;
513
Douglas Gregor1d381132009-07-06 15:59:29 +0000514 case Type::ConstantArrayWithExpr:
515 case Type::ConstantArrayWithoutExpr:
Steve Naroff83c13012007-08-30 01:06:46 +0000516 case Type::ConstantArray: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000517 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Naroff83c13012007-08-30 01:06:46 +0000518
Chris Lattner8cd0e932008-03-05 18:54:05 +0000519 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000520 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000521 Align = EltInfo.second;
522 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000523 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000524 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000525 case Type::Vector: {
526 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000527 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000528 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000529 Align = Width;
Nate Begeman7903d052009-01-18 06:42:49 +0000530 // If the alignment is not a power of 2, round up to the next power of 2.
531 // This happens for non-power-of-2 length vectors.
532 // FIXME: this should probably be a target property.
533 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000534 break;
535 }
536
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000537 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000538 switch (cast<BuiltinType>(T)->getKind()) {
539 default: assert(0 && "Unknown builtin type!");
540 case BuiltinType::Void:
Douglas Gregorab380272009-04-30 17:32:17 +0000541 // GCC extension: alignof(void) = 8 bits.
542 Width = 0;
543 Align = 8;
544 break;
545
Chris Lattnerb66237b2007-12-19 19:23:28 +0000546 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000547 Width = Target.getBoolWidth();
548 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000549 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000550 case BuiltinType::Char_S:
551 case BuiltinType::Char_U:
552 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000553 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000554 Width = Target.getCharWidth();
555 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000556 break;
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000557 case BuiltinType::WChar:
558 Width = Target.getWCharWidth();
559 Align = Target.getWCharAlign();
560 break;
Alisdair Meredith2bcacb62009-07-14 06:30:34 +0000561 case BuiltinType::Char16:
562 Width = Target.getChar16Width();
563 Align = Target.getChar16Align();
564 break;
565 case BuiltinType::Char32:
566 Width = Target.getChar32Width();
567 Align = Target.getChar32Align();
568 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000569 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000570 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000571 Width = Target.getShortWidth();
572 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000573 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000574 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000575 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000576 Width = Target.getIntWidth();
577 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000578 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000579 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000580 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000581 Width = Target.getLongWidth();
582 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000583 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000584 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000585 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000586 Width = Target.getLongLongWidth();
587 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000588 break;
Chris Lattner4b11cc22009-04-30 02:55:13 +0000589 case BuiltinType::Int128:
590 case BuiltinType::UInt128:
591 Width = 128;
592 Align = 128; // int128_t is 128-bit aligned on all targets.
593 break;
Chris Lattnerb66237b2007-12-19 19:23:28 +0000594 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000595 Width = Target.getFloatWidth();
596 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000597 break;
598 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000599 Width = Target.getDoubleWidth();
600 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000601 break;
602 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000603 Width = Target.getLongDoubleWidth();
604 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000605 break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000606 case BuiltinType::NullPtr:
607 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
608 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redlc4cce782009-05-27 19:34:06 +0000609 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000610 }
611 break;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000612 case Type::FixedWidthInt:
613 // FIXME: This isn't precisely correct; the width/alignment should depend
614 // on the available types for the target
615 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattnere9174982009-02-15 21:20:13 +0000616 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000617 Align = Width;
618 break;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000619 case Type::ExtQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000620 // FIXME: Pointers into different addr spaces could have different sizes and
621 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000622 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffc75c1a82009-06-17 22:40:22 +0000623 case Type::ObjCObjectPointer:
Chris Lattner1d78a862008-04-07 07:01:58 +0000624 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000625 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000626 break;
Steve Naroff62f09f52008-09-24 15:05:44 +0000627 case Type::BlockPointer: {
628 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
629 Width = Target.getPointerWidth(AS);
630 Align = Target.getPointerAlign(AS);
631 break;
632 }
Chris Lattner461a6c52008-03-08 08:34:58 +0000633 case Type::Pointer: {
634 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000635 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000636 Align = Target.getPointerAlign(AS);
637 break;
638 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000639 case Type::LValueReference:
640 case Type::RValueReference:
Chris Lattner4b009652007-07-25 00:24:17 +0000641 // "When applied to a reference or a reference type, the result is the size
642 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000643 // FIXME: This is wrong for struct layout: a reference in a struct has
644 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000645 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl75555032009-01-24 21:16:55 +0000646 case Type::MemberPointer: {
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000647 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
648 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
649 // If we ever want to support other ABIs this needs to be abstracted.
650
Sebastian Redl75555032009-01-24 21:16:55 +0000651 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000652 std::pair<uint64_t, unsigned> PtrDiffInfo =
653 getTypeInfo(getPointerDiffType());
654 Width = PtrDiffInfo.first;
Sebastian Redl75555032009-01-24 21:16:55 +0000655 if (Pointee->isFunctionType())
656 Width *= 2;
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000657 Align = PtrDiffInfo.second;
658 break;
Sebastian Redl75555032009-01-24 21:16:55 +0000659 }
Chris Lattner4b009652007-07-25 00:24:17 +0000660 case Type::Complex: {
661 // Complex types have the same alignment as their elements, but twice the
662 // size.
663 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000664 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000665 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000666 Align = EltInfo.second;
667 break;
668 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000669 case Type::ObjCInterface: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000670 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel4b6bf702008-06-04 21:54:36 +0000671 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
672 Width = Layout.getSize();
673 Align = Layout.getAlignment();
674 break;
675 }
Douglas Gregor4fa58902009-02-26 23:50:07 +0000676 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000677 case Type::Enum: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000678 const TagType *TT = cast<TagType>(T);
679
680 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattnerfd799692008-08-09 21:35:13 +0000681 Width = 1;
682 Align = 1;
683 break;
684 }
685
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000686 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000687 return getTypeInfo(ET->getDecl()->getIntegerType());
688
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000689 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000690 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
691 Width = Layout.getSize();
692 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000693 break;
694 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000695
Douglas Gregorab380272009-04-30 17:32:17 +0000696 case Type::Typedef: {
697 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000698 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregorab380272009-04-30 17:32:17 +0000699 Align = Aligned->getAlignment();
700 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
701 } else
702 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordd13e842009-03-30 22:58:21 +0000703 break;
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000704 }
Douglas Gregorab380272009-04-30 17:32:17 +0000705
706 case Type::TypeOfExpr:
707 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
708 .getTypePtr());
709
710 case Type::TypeOf:
711 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
712
Anders Carlsson93ab5332009-06-24 19:06:50 +0000713 case Type::Decltype:
714 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
715 .getTypePtr());
716
Douglas Gregorab380272009-04-30 17:32:17 +0000717 case Type::QualifiedName:
718 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
719
720 case Type::TemplateSpecialization:
721 assert(getCanonicalType(T) != T &&
722 "Cannot request the size of a dependent type");
723 // FIXME: this is likely to be wrong once we support template
724 // aliases, since a template alias could refer to a typedef that
725 // has an __aligned__ attribute on it.
726 return getTypeInfo(getCanonicalType(T));
727 }
Chris Lattner4b009652007-07-25 00:24:17 +0000728
729 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000730 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000731}
732
Chris Lattner83165b52009-01-27 18:08:34 +0000733/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
734/// type for the current target in bits. This can be different than the ABI
735/// alignment in cases where it is beneficial for performance to overalign
736/// a data type.
737unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
738 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman66c9edf2009-05-25 21:27:19 +0000739
740 // Double and long long should be naturally aligned if possible.
741 if (const ComplexType* CT = T->getAsComplexType())
742 T = CT->getElementType().getTypePtr();
743 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
744 T->isSpecificBuiltinType(BuiltinType::LongLong))
745 return std::max(ABIAlign, (unsigned)getTypeSize(T));
746
Chris Lattner83165b52009-01-27 18:08:34 +0000747 return ABIAlign;
748}
749
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000750static void CollectLocalObjCIvars(ASTContext *Ctx,
751 const ObjCInterfaceDecl *OI,
752 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000753 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
754 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner9329cf52009-03-31 08:48:01 +0000755 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000756 if (!IVDecl->isInvalidDecl())
757 Fields.push_back(cast<FieldDecl>(IVDecl));
758 }
759}
760
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000761void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
762 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
763 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
764 CollectObjCIvars(SuperClass, Fields);
765 CollectLocalObjCIvars(this, OI, Fields);
766}
767
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000768/// ShallowCollectObjCIvars -
769/// Collect all ivars, including those synthesized, in the current class.
770///
771void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
772 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
773 bool CollectSynthesized) {
774 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
775 E = OI->ivar_end(); I != E; ++I) {
776 Ivars.push_back(*I);
777 }
778 if (CollectSynthesized)
779 CollectSynthesizedIvars(OI, Ivars);
780}
781
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +0000782void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
783 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000784 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
785 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +0000786 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
787 Ivars.push_back(Ivar);
788
789 // Also look into nested protocols.
790 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
791 E = PD->protocol_end(); P != E; ++P)
792 CollectProtocolSynthesizedIvars(*P, Ivars);
793}
794
795/// CollectSynthesizedIvars -
796/// This routine collect synthesized ivars for the designated class.
797///
798void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
799 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000800 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
801 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +0000802 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
803 Ivars.push_back(Ivar);
804 }
805 // Also look into interface's protocol list for properties declared
806 // in the protocol and whose ivars are synthesized.
807 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
808 PE = OI->protocol_end(); P != PE; ++P) {
809 ObjCProtocolDecl *PD = (*P);
810 CollectProtocolSynthesizedIvars(PD, Ivars);
811 }
812}
813
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000814unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
815 unsigned count = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000816 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
817 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000818 if ((*I)->getPropertyIvarDecl())
819 ++count;
820
821 // Also look into nested protocols.
822 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
823 E = PD->protocol_end(); P != E; ++P)
824 count += CountProtocolSynthesizedIvars(*P);
825 return count;
826}
827
828unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
829{
830 unsigned count = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000831 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
832 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000833 if ((*I)->getPropertyIvarDecl())
834 ++count;
835 }
836 // Also look into interface's protocol list for properties declared
837 // in the protocol and whose ivars are synthesized.
838 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
839 PE = OI->protocol_end(); P != PE; ++P) {
840 ObjCProtocolDecl *PD = (*P);
841 count += CountProtocolSynthesizedIvars(PD);
842 }
843 return count;
844}
845
Argiris Kirtzidis3a4d9832009-07-21 00:05:53 +0000846/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
847ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
848 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
849 I = ObjCImpls.find(D);
850 if (I != ObjCImpls.end())
851 return cast<ObjCImplementationDecl>(I->second);
852 return 0;
853}
854/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
855ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
856 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
857 I = ObjCImpls.find(D);
858 if (I != ObjCImpls.end())
859 return cast<ObjCCategoryImplDecl>(I->second);
860 return 0;
861}
862
863/// \brief Set the implementation of ObjCInterfaceDecl.
864void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
865 ObjCImplementationDecl *ImplD) {
866 assert(IFaceD && ImplD && "Passed null params");
867 ObjCImpls[IFaceD] = ImplD;
868}
869/// \brief Set the implementation of ObjCCategoryDecl.
870void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
871 ObjCCategoryImplDecl *ImplD) {
872 assert(CatD && ImplD && "Passed null params");
873 ObjCImpls[CatD] = ImplD;
874}
875
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000876/// getInterfaceLayoutImpl - Get or compute information about the
877/// layout of the given interface.
878///
879/// \param Impl - If given, also include the layout of the interface's
880/// implementation. This may differ by including synthesized ivars.
Devang Patel4b6bf702008-06-04 21:54:36 +0000881const ASTRecordLayout &
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000882ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
883 const ObjCImplementationDecl *Impl) {
Daniel Dunbar94d2ede2009-05-03 13:15:50 +0000884 assert(!D->isForwardDecl() && "Invalid interface decl!");
885
Devang Patel4b6bf702008-06-04 21:54:36 +0000886 // Look up this layout, if already laid out, return what we have.
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000887 ObjCContainerDecl *Key =
888 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
889 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
890 return *Entry;
Devang Patel4b6bf702008-06-04 21:54:36 +0000891
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000892 // Add in synthesized ivar count if laying out an implementation.
893 if (Impl) {
Anders Carlsson5d382582009-07-18 21:19:52 +0000894 unsigned FieldCount = D->ivar_size();
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000895 unsigned SynthCount = CountSynthesizedIvars(D);
896 FieldCount += SynthCount;
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000897 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000898 // entry. Note we can't cache this because we simply free all
899 // entries later; however we shouldn't look up implementations
900 // frequently.
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000901 if (SynthCount == 0)
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000902 return getObjCLayout(D, 0);
903 }
904
Anders Carlsson5d382582009-07-18 21:19:52 +0000905 const ASTRecordLayout *NewEntry =
906 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
907 ObjCLayouts[Key] = NewEntry;
908
Devang Patel4b6bf702008-06-04 21:54:36 +0000909 return *NewEntry;
910}
911
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000912const ASTRecordLayout &
913ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
914 return getObjCLayout(D, 0);
915}
916
917const ASTRecordLayout &
918ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
919 return getObjCLayout(D->getClassInterface(), D);
920}
921
Devang Patel7a78e432007-11-01 19:11:01 +0000922/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000923/// specified record (struct/union/class), which indicates its size and field
924/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000925const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek46a837c2008-09-05 17:16:31 +0000926 D = D->getDefinition(*this);
927 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000928
Chris Lattner4b009652007-07-25 00:24:17 +0000929 // Look up this layout, if already laid out, return what we have.
Eli Friedman774cb992009-07-22 20:29:16 +0000930 // Note that we can't save a reference to the entry because this function
931 // is recursive.
932 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000933 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000934
Anders Carlsson5d382582009-07-18 21:19:52 +0000935 const ASTRecordLayout *NewEntry =
936 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman774cb992009-07-22 20:29:16 +0000937 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson5d382582009-07-18 21:19:52 +0000938
Chris Lattner4b009652007-07-25 00:24:17 +0000939 return *NewEntry;
940}
941
Chris Lattner4b009652007-07-25 00:24:17 +0000942//===----------------------------------------------------------------------===//
943// Type creation/memoization methods
944//===----------------------------------------------------------------------===//
945
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000946QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000947 QualType CanT = getCanonicalType(T);
948 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000949 return T;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000950
951 // If we are composing extended qualifiers together, merge together into one
952 // ExtQualType node.
953 unsigned CVRQuals = T.getCVRQualifiers();
954 QualType::GCAttrTypes GCAttr = QualType::GCNone;
955 Type *TypeNode = T.getTypePtr();
Chris Lattner35fef522008-02-20 20:55:12 +0000956
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000957 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
958 // If this type already has an address space specified, it cannot get
959 // another one.
960 assert(EQT->getAddressSpace() == 0 &&
961 "Type cannot be in multiple addr spaces!");
962 GCAttr = EQT->getObjCGCAttr();
963 TypeNode = EQT->getBaseType();
964 }
Chris Lattner35fef522008-02-20 20:55:12 +0000965
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000966 // Check if we've already instantiated this type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000967 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000968 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000969 void *InsertPos = 0;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000970 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000971 return QualType(EXTQy, CVRQuals);
972
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000973 // If the base type isn't canonical, this won't be a canonical type either,
974 // so fill in the canonical type field.
975 QualType Canonical;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000976 if (!TypeNode->isCanonical()) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000977 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000978
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000979 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000980 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000981 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000982 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000983 ExtQualType *New =
984 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000985 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000986 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000987 return QualType(New, CVRQuals);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000988}
989
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000990QualType ASTContext::getObjCGCQualType(QualType T,
991 QualType::GCAttrTypes GCAttr) {
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000992 QualType CanT = getCanonicalType(T);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000993 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000994 return T;
995
Fariborz Jahanian143b0082009-06-03 17:15:17 +0000996 if (T->isPointerType()) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000997 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff79ae19a2009-07-14 18:25:06 +0000998 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian143b0082009-06-03 17:15:17 +0000999 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1000 return getPointerType(ResultType);
1001 }
1002 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001003 // If we are composing extended qualifiers together, merge together into one
1004 // ExtQualType node.
1005 unsigned CVRQuals = T.getCVRQualifiers();
1006 Type *TypeNode = T.getTypePtr();
1007 unsigned AddressSpace = 0;
1008
1009 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1010 // If this type already has an address space specified, it cannot get
1011 // another one.
1012 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1013 "Type cannot be in multiple addr spaces!");
1014 AddressSpace = EQT->getAddressSpace();
1015 TypeNode = EQT->getBaseType();
1016 }
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001017
1018 // Check if we've already instantiated an gc qual'd type of this type.
1019 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001020 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001021 void *InsertPos = 0;
1022 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001023 return QualType(EXTQy, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001024
1025 // If the base type isn't canonical, this won't be a canonical type either,
1026 // so fill in the canonical type field.
Eli Friedman94fcc9a2009-02-27 23:04:43 +00001027 // FIXME: Isn't this also not canonical if the base type is a array
1028 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001029 QualType Canonical;
1030 if (!T->isCanonical()) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001031 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001032
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001033 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001034 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1035 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1036 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001037 ExtQualType *New =
1038 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001039 ExtQualTypes.InsertNode(New, InsertPos);
1040 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +00001041 return QualType(New, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +00001042}
Chris Lattner4b009652007-07-25 00:24:17 +00001043
1044/// getComplexType - Return the uniqued reference to the type for a complex
1045/// number with the specified element type.
1046QualType ASTContext::getComplexType(QualType T) {
1047 // Unique pointers, to guarantee there is only one pointer of a particular
1048 // structure.
1049 llvm::FoldingSetNodeID ID;
1050 ComplexType::Profile(ID, T);
1051
1052 void *InsertPos = 0;
1053 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1054 return QualType(CT, 0);
1055
1056 // If the pointee type isn't canonical, this won't be a canonical type either,
1057 // so fill in the canonical type field.
1058 QualType Canonical;
1059 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001060 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +00001061
1062 // Get the new insert position for the node we care about.
1063 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001064 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001065 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001066 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001067 Types.push_back(New);
1068 ComplexTypes.InsertNode(New, InsertPos);
1069 return QualType(New, 0);
1070}
1071
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001072QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1073 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1074 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1075 FixedWidthIntType *&Entry = Map[Width];
1076 if (!Entry)
1077 Entry = new FixedWidthIntType(Width, Signed);
1078 return QualType(Entry, 0);
1079}
Chris Lattner4b009652007-07-25 00:24:17 +00001080
1081/// getPointerType - Return the uniqued reference to the type for a pointer to
1082/// the specified type.
1083QualType ASTContext::getPointerType(QualType T) {
1084 // Unique pointers, to guarantee there is only one pointer of a particular
1085 // structure.
1086 llvm::FoldingSetNodeID ID;
1087 PointerType::Profile(ID, T);
1088
1089 void *InsertPos = 0;
1090 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1091 return QualType(PT, 0);
1092
1093 // If the pointee type isn't canonical, this won't be a canonical type either,
1094 // so fill in the canonical type field.
1095 QualType Canonical;
1096 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001097 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +00001098
1099 // Get the new insert position for the node we care about.
1100 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001101 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001102 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001103 PointerType *New = new (*this,8) PointerType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001104 Types.push_back(New);
1105 PointerTypes.InsertNode(New, InsertPos);
1106 return QualType(New, 0);
1107}
1108
Steve Naroff7aa54752008-08-27 16:04:49 +00001109/// getBlockPointerType - Return the uniqued reference to the type for
1110/// a pointer to the specified block.
1111QualType ASTContext::getBlockPointerType(QualType T) {
Steve Narofffd5b19d2008-08-28 19:20:44 +00001112 assert(T->isFunctionType() && "block of function types only");
1113 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff7aa54752008-08-27 16:04:49 +00001114 // structure.
1115 llvm::FoldingSetNodeID ID;
1116 BlockPointerType::Profile(ID, T);
1117
1118 void *InsertPos = 0;
1119 if (BlockPointerType *PT =
1120 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1121 return QualType(PT, 0);
1122
Steve Narofffd5b19d2008-08-28 19:20:44 +00001123 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff7aa54752008-08-27 16:04:49 +00001124 // type either so fill in the canonical type field.
1125 QualType Canonical;
1126 if (!T->isCanonical()) {
1127 Canonical = getBlockPointerType(getCanonicalType(T));
1128
1129 // Get the new insert position for the node we care about.
1130 BlockPointerType *NewIP =
1131 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001132 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff7aa54752008-08-27 16:04:49 +00001133 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001134 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff7aa54752008-08-27 16:04:49 +00001135 Types.push_back(New);
1136 BlockPointerTypes.InsertNode(New, InsertPos);
1137 return QualType(New, 0);
1138}
1139
Sebastian Redlce6fff02009-03-16 23:22:08 +00001140/// getLValueReferenceType - Return the uniqued reference to the type for an
1141/// lvalue reference to the specified type.
1142QualType ASTContext::getLValueReferenceType(QualType T) {
Chris Lattner4b009652007-07-25 00:24:17 +00001143 // Unique pointers, to guarantee there is only one pointer of a particular
1144 // structure.
1145 llvm::FoldingSetNodeID ID;
1146 ReferenceType::Profile(ID, T);
1147
1148 void *InsertPos = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001149 if (LValueReferenceType *RT =
1150 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001151 return QualType(RT, 0);
Sebastian Redlce6fff02009-03-16 23:22:08 +00001152
Chris Lattner4b009652007-07-25 00:24:17 +00001153 // If the referencee type isn't canonical, this won't be a canonical type
1154 // either, so fill in the canonical type field.
1155 QualType Canonical;
1156 if (!T->isCanonical()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00001157 Canonical = getLValueReferenceType(getCanonicalType(T));
1158
Chris Lattner4b009652007-07-25 00:24:17 +00001159 // Get the new insert position for the node we care about.
Sebastian Redlce6fff02009-03-16 23:22:08 +00001160 LValueReferenceType *NewIP =
1161 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001162 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001163 }
1164
Sebastian Redlce6fff02009-03-16 23:22:08 +00001165 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001166 Types.push_back(New);
Sebastian Redlce6fff02009-03-16 23:22:08 +00001167 LValueReferenceTypes.InsertNode(New, InsertPos);
1168 return QualType(New, 0);
1169}
1170
1171/// getRValueReferenceType - Return the uniqued reference to the type for an
1172/// rvalue reference to the specified type.
1173QualType ASTContext::getRValueReferenceType(QualType T) {
1174 // Unique pointers, to guarantee there is only one pointer of a particular
1175 // structure.
1176 llvm::FoldingSetNodeID ID;
1177 ReferenceType::Profile(ID, T);
1178
1179 void *InsertPos = 0;
1180 if (RValueReferenceType *RT =
1181 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1182 return QualType(RT, 0);
1183
1184 // If the referencee type isn't canonical, this won't be a canonical type
1185 // either, so fill in the canonical type field.
1186 QualType Canonical;
1187 if (!T->isCanonical()) {
1188 Canonical = getRValueReferenceType(getCanonicalType(T));
1189
1190 // Get the new insert position for the node we care about.
1191 RValueReferenceType *NewIP =
1192 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1193 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1194 }
1195
1196 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1197 Types.push_back(New);
1198 RValueReferenceTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001199 return QualType(New, 0);
1200}
1201
Sebastian Redl75555032009-01-24 21:16:55 +00001202/// getMemberPointerType - Return the uniqued reference to the type for a
1203/// member pointer to the specified type, in the specified class.
1204QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1205{
1206 // Unique pointers, to guarantee there is only one pointer of a particular
1207 // structure.
1208 llvm::FoldingSetNodeID ID;
1209 MemberPointerType::Profile(ID, T, Cls);
1210
1211 void *InsertPos = 0;
1212 if (MemberPointerType *PT =
1213 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1214 return QualType(PT, 0);
1215
1216 // If the pointee or class type isn't canonical, this won't be a canonical
1217 // type either, so fill in the canonical type field.
1218 QualType Canonical;
1219 if (!T->isCanonical()) {
1220 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1221
1222 // Get the new insert position for the node we care about.
1223 MemberPointerType *NewIP =
1224 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1225 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1226 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001227 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redl75555032009-01-24 21:16:55 +00001228 Types.push_back(New);
1229 MemberPointerTypes.InsertNode(New, InsertPos);
1230 return QualType(New, 0);
1231}
1232
Steve Naroff83c13012007-08-30 01:06:46 +00001233/// getConstantArrayType - Return the unique reference to the type for an
1234/// array of the specified element type.
1235QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner08bea472009-05-13 04:12:56 +00001236 const llvm::APInt &ArySizeIn,
Steve Naroff24c9b982007-08-30 18:10:14 +00001237 ArrayType::ArraySizeModifier ASM,
1238 unsigned EltTypeQuals) {
Eli Friedmanb4c71b32009-05-29 20:17:55 +00001239 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1240 "Constant array of VLAs is illegal!");
1241
Chris Lattner08bea472009-05-13 04:12:56 +00001242 // Convert the array size into a canonical width matching the pointer size for
1243 // the target.
1244 llvm::APInt ArySize(ArySizeIn);
1245 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1246
Chris Lattner4b009652007-07-25 00:24:17 +00001247 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001248 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001249
1250 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +00001251 if (ConstantArrayType *ATP =
1252 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001253 return QualType(ATP, 0);
1254
1255 // If the element type isn't canonical, this won't be a canonical type either,
1256 // so fill in the canonical type field.
1257 QualType Canonical;
1258 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001259 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +00001260 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001261 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +00001262 ConstantArrayType *NewIP =
1263 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001264 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001265 }
1266
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001267 ConstantArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001268 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001269 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001270 Types.push_back(New);
1271 return QualType(New, 0);
1272}
1273
Douglas Gregor1d381132009-07-06 15:59:29 +00001274/// getConstantArrayWithExprType - Return a reference to the type for
1275/// an array of the specified element type.
1276QualType
1277ASTContext::getConstantArrayWithExprType(QualType EltTy,
1278 const llvm::APInt &ArySizeIn,
1279 Expr *ArySizeExpr,
1280 ArrayType::ArraySizeModifier ASM,
1281 unsigned EltTypeQuals,
1282 SourceRange Brackets) {
1283 // Convert the array size into a canonical width matching the pointer
1284 // size for the target.
1285 llvm::APInt ArySize(ArySizeIn);
1286 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1287
1288 // Compute the canonical ConstantArrayType.
1289 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1290 ArySize, ASM, EltTypeQuals);
1291 // Since we don't unique expressions, it isn't possible to unique VLA's
1292 // that have an expression provided for their size.
1293 ConstantArrayWithExprType *New =
1294 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1295 ArySize, ArySizeExpr,
1296 ASM, EltTypeQuals, Brackets);
1297 Types.push_back(New);
1298 return QualType(New, 0);
1299}
1300
1301/// getConstantArrayWithoutExprType - Return a reference to the type for
1302/// an array of the specified element type.
1303QualType
1304ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1305 const llvm::APInt &ArySizeIn,
1306 ArrayType::ArraySizeModifier ASM,
1307 unsigned EltTypeQuals) {
1308 // Convert the array size into a canonical width matching the pointer
1309 // size for the target.
1310 llvm::APInt ArySize(ArySizeIn);
1311 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1312
1313 // Compute the canonical ConstantArrayType.
1314 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1315 ArySize, ASM, EltTypeQuals);
1316 ConstantArrayWithoutExprType *New =
1317 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1318 ArySize, ASM, EltTypeQuals);
1319 Types.push_back(New);
1320 return QualType(New, 0);
1321}
1322
Steve Naroffe2579e32007-08-30 18:14:25 +00001323/// getVariableArrayType - Returns a non-unique reference to the type for a
1324/// variable array of the specified element type.
Douglas Gregor1d381132009-07-06 15:59:29 +00001325QualType ASTContext::getVariableArrayType(QualType EltTy,
1326 Expr *NumElts,
Steve Naroff24c9b982007-08-30 18:10:14 +00001327 ArrayType::ArraySizeModifier ASM,
Douglas Gregor1d381132009-07-06 15:59:29 +00001328 unsigned EltTypeQuals,
1329 SourceRange Brackets) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001330 // Since we don't unique expressions, it isn't possible to unique VLA's
1331 // that have an expression provided for their size.
1332
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001333 VariableArrayType *New =
Douglas Gregor1d381132009-07-06 15:59:29 +00001334 new(*this,8)VariableArrayType(EltTy, QualType(),
1335 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedman8ff07782008-02-15 18:16:39 +00001336
1337 VariableArrayTypes.push_back(New);
1338 Types.push_back(New);
1339 return QualType(New, 0);
1340}
1341
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001342/// getDependentSizedArrayType - Returns a non-unique reference to
1343/// the type for a dependently-sized array of the specified element
1344/// type. FIXME: We will need these to be uniqued, or at least
1345/// comparable, at some point.
Douglas Gregor1d381132009-07-06 15:59:29 +00001346QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1347 Expr *NumElts,
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001348 ArrayType::ArraySizeModifier ASM,
Douglas Gregor1d381132009-07-06 15:59:29 +00001349 unsigned EltTypeQuals,
1350 SourceRange Brackets) {
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001351 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1352 "Size must be type- or value-dependent!");
1353
1354 // Since we don't unique expressions, it isn't possible to unique
1355 // dependently-sized array types.
1356
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001357 DependentSizedArrayType *New =
Douglas Gregor1d381132009-07-06 15:59:29 +00001358 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1359 NumElts, ASM, EltTypeQuals,
1360 Brackets);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001361
1362 DependentSizedArrayTypes.push_back(New);
1363 Types.push_back(New);
1364 return QualType(New, 0);
1365}
1366
Eli Friedman8ff07782008-02-15 18:16:39 +00001367QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1368 ArrayType::ArraySizeModifier ASM,
1369 unsigned EltTypeQuals) {
1370 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001371 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001372
1373 void *InsertPos = 0;
1374 if (IncompleteArrayType *ATP =
1375 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1376 return QualType(ATP, 0);
1377
1378 // If the element type isn't canonical, this won't be a canonical type
1379 // either, so fill in the canonical type field.
1380 QualType Canonical;
1381
1382 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001383 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001384 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001385
1386 // Get the new insert position for the node we care about.
1387 IncompleteArrayType *NewIP =
1388 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001389 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001390 }
Eli Friedman8ff07782008-02-15 18:16:39 +00001391
Douglas Gregor1d381132009-07-06 15:59:29 +00001392 IncompleteArrayType *New
1393 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1394 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001395
1396 IncompleteArrayTypes.InsertNode(New, InsertPos);
1397 Types.push_back(New);
1398 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +00001399}
1400
Chris Lattner4b009652007-07-25 00:24:17 +00001401/// getVectorType - Return the unique reference to a vector type of
1402/// the specified element type and size. VectorType must be a built-in type.
1403QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1404 BuiltinType *baseType;
1405
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001406 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +00001407 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1408
1409 // Check if we've already instantiated a vector of this type.
1410 llvm::FoldingSetNodeID ID;
1411 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1412 void *InsertPos = 0;
1413 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1414 return QualType(VTP, 0);
1415
1416 // If the element type isn't canonical, this won't be a canonical type either,
1417 // so fill in the canonical type field.
1418 QualType Canonical;
1419 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001420 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001421
1422 // Get the new insert position for the node we care about.
1423 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001424 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001425 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001426 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001427 VectorTypes.InsertNode(New, InsertPos);
1428 Types.push_back(New);
1429 return QualType(New, 0);
1430}
1431
Nate Begemanaf6ed502008-04-18 23:10:10 +00001432/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +00001433/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001434QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +00001435 BuiltinType *baseType;
1436
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001437 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +00001438 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +00001439
1440 // Check if we've already instantiated a vector of this type.
1441 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +00001442 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +00001443 void *InsertPos = 0;
1444 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1445 return QualType(VTP, 0);
1446
1447 // If the element type isn't canonical, this won't be a canonical type either,
1448 // so fill in the canonical type field.
1449 QualType Canonical;
1450 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001451 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001452
1453 // Get the new insert position for the node we care about.
1454 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001455 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001456 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001457 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001458 VectorTypes.InsertNode(New, InsertPos);
1459 Types.push_back(New);
1460 return QualType(New, 0);
1461}
1462
Douglas Gregor2a2e0402009-06-17 21:51:59 +00001463QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1464 Expr *SizeExpr,
1465 SourceLocation AttrLoc) {
1466 DependentSizedExtVectorType *New =
1467 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1468 SizeExpr, AttrLoc);
1469
1470 DependentSizedExtVectorTypes.push_back(New);
1471 Types.push_back(New);
1472 return QualType(New, 0);
1473}
1474
Douglas Gregor4fa58902009-02-26 23:50:07 +00001475/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattner4b009652007-07-25 00:24:17 +00001476///
Douglas Gregor4fa58902009-02-26 23:50:07 +00001477QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Chris Lattner4b009652007-07-25 00:24:17 +00001478 // Unique functions, to guarantee there is only one function of a particular
1479 // structure.
1480 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001481 FunctionNoProtoType::Profile(ID, ResultTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001482
1483 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001484 if (FunctionNoProtoType *FT =
1485 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001486 return QualType(FT, 0);
1487
1488 QualType Canonical;
1489 if (!ResultTy->isCanonical()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00001490 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001491
1492 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001493 FunctionNoProtoType *NewIP =
1494 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001495 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001496 }
1497
Douglas Gregor4fa58902009-02-26 23:50:07 +00001498 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001499 Types.push_back(New);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001500 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001501 return QualType(New, 0);
1502}
1503
1504/// getFunctionType - Return a normal function type with a typed argument
1505/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner2fda0ed2008-10-05 17:34:18 +00001506QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001507 unsigned NumArgs, bool isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001508 unsigned TypeQuals, bool hasExceptionSpec,
1509 bool hasAnyExceptionSpec, unsigned NumExs,
1510 const QualType *ExArray) {
Chris Lattner4b009652007-07-25 00:24:17 +00001511 // Unique functions, to guarantee there is only one function of a particular
1512 // structure.
1513 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001514 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001515 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1516 NumExs, ExArray);
Chris Lattner4b009652007-07-25 00:24:17 +00001517
1518 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001519 if (FunctionProtoType *FTP =
1520 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001521 return QualType(FTP, 0);
Sebastian Redl2767d882009-05-27 22:11:52 +00001522
1523 // Determine whether the type being created is already canonical or not.
Chris Lattner4b009652007-07-25 00:24:17 +00001524 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl2767d882009-05-27 22:11:52 +00001525 if (hasExceptionSpec)
1526 isCanonical = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001527 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1528 if (!ArgArray[i]->isCanonical())
1529 isCanonical = false;
1530
1531 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl2767d882009-05-27 22:11:52 +00001532 // The exception spec is not part of the canonical type.
Chris Lattner4b009652007-07-25 00:24:17 +00001533 QualType Canonical;
1534 if (!isCanonical) {
1535 llvm::SmallVector<QualType, 16> CanonicalArgs;
1536 CanonicalArgs.reserve(NumArgs);
1537 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001538 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl2767d882009-05-27 22:11:52 +00001539
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001540 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad9e6bef42009-05-21 09:52:38 +00001541 CanonicalArgs.data(), NumArgs,
Sebastian Redlba9a3712009-05-06 23:27:55 +00001542 isVariadic, TypeQuals);
Sebastian Redl2767d882009-05-27 22:11:52 +00001543
Chris Lattner4b009652007-07-25 00:24:17 +00001544 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001545 FunctionProtoType *NewIP =
1546 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001547 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001548 }
Sebastian Redl2767d882009-05-27 22:11:52 +00001549
Douglas Gregor4fa58902009-02-26 23:50:07 +00001550 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl2767d882009-05-27 22:11:52 +00001551 // for two variable size arrays (for parameter and exception types) at the
1552 // end of them.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001553 FunctionProtoType *FTP =
Sebastian Redl2767d882009-05-27 22:11:52 +00001554 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1555 NumArgs*sizeof(QualType) +
1556 NumExs*sizeof(QualType), 8);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001557 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001558 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1559 ExArray, NumExs, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001560 Types.push_back(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001561 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001562 return QualType(FTP, 0);
1563}
1564
Douglas Gregor1d661552008-04-13 21:07:44 +00001565/// getTypeDeclType - Return the unique reference to the type for the
1566/// specified type declaration.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001567QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001568 assert(Decl && "Passed null for Decl param");
Douglas Gregor1d661552008-04-13 21:07:44 +00001569 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1570
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001571 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001572 return getTypedefType(Typedef);
Douglas Gregora4918772009-02-05 23:33:38 +00001573 else if (isa<TemplateTypeParmDecl>(Decl)) {
1574 assert(false && "Template type parameter types are always available.");
1575 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001576 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001577
Douglas Gregor2e047592009-02-28 01:32:25 +00001578 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001579 if (PrevDecl)
1580 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001581 else
1582 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek46a837c2008-09-05 17:16:31 +00001583 }
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001584 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1585 if (PrevDecl)
1586 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001587 else
1588 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001589 }
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001590 else
Douglas Gregor1d661552008-04-13 21:07:44 +00001591 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001592
Ted Kremenek46a837c2008-09-05 17:16:31 +00001593 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001594 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +00001595}
1596
Chris Lattner4b009652007-07-25 00:24:17 +00001597/// getTypedefType - Return the unique reference to the type for the
1598/// specified typename decl.
1599QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1600 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1601
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001602 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001603 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001604 Types.push_back(Decl->TypeForDecl);
1605 return QualType(Decl->TypeForDecl, 0);
1606}
1607
Douglas Gregora4918772009-02-05 23:33:38 +00001608/// \brief Retrieve the template type parameter type for a template
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001609/// parameter or parameter pack with the given depth, index, and (optionally)
1610/// name.
Douglas Gregora4918772009-02-05 23:33:38 +00001611QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001612 bool ParameterPack,
Douglas Gregora4918772009-02-05 23:33:38 +00001613 IdentifierInfo *Name) {
1614 llvm::FoldingSetNodeID ID;
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001615 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregora4918772009-02-05 23:33:38 +00001616 void *InsertPos = 0;
1617 TemplateTypeParmType *TypeParm
1618 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1619
1620 if (TypeParm)
1621 return QualType(TypeParm, 0);
1622
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001623 if (Name) {
1624 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1625 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1626 Name, Canon);
1627 } else
1628 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregora4918772009-02-05 23:33:38 +00001629
1630 Types.push_back(TypeParm);
1631 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1632
1633 return QualType(TypeParm, 0);
1634}
1635
Douglas Gregor8e458f42009-02-09 18:46:07 +00001636QualType
Douglas Gregordd13e842009-03-30 22:58:21 +00001637ASTContext::getTemplateSpecializationType(TemplateName Template,
1638 const TemplateArgument *Args,
1639 unsigned NumArgs,
1640 QualType Canon) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001641 if (!Canon.isNull())
1642 Canon = getCanonicalType(Canon);
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001643
Douglas Gregor8e458f42009-02-09 18:46:07 +00001644 llvm::FoldingSetNodeID ID;
Douglas Gregordd13e842009-03-30 22:58:21 +00001645 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001646
Douglas Gregor8e458f42009-02-09 18:46:07 +00001647 void *InsertPos = 0;
Douglas Gregordd13e842009-03-30 22:58:21 +00001648 TemplateSpecializationType *Spec
1649 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001650
1651 if (Spec)
1652 return QualType(Spec, 0);
1653
Douglas Gregordd13e842009-03-30 22:58:21 +00001654 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001655 sizeof(TemplateArgument) * NumArgs),
1656 8);
Douglas Gregordd13e842009-03-30 22:58:21 +00001657 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001658 Types.push_back(Spec);
Douglas Gregordd13e842009-03-30 22:58:21 +00001659 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001660
1661 return QualType(Spec, 0);
1662}
1663
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001664QualType
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001665ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001666 QualType NamedType) {
1667 llvm::FoldingSetNodeID ID;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001668 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001669
1670 void *InsertPos = 0;
1671 QualifiedNameType *T
1672 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1673 if (T)
1674 return QualType(T, 0);
1675
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001676 T = new (*this) QualifiedNameType(NNS, NamedType,
1677 getCanonicalType(NamedType));
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001678 Types.push_back(T);
1679 QualifiedNameTypes.InsertNode(T, InsertPos);
1680 return QualType(T, 0);
1681}
1682
Douglas Gregord3022602009-03-27 23:10:48 +00001683QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1684 const IdentifierInfo *Name,
1685 QualType Canon) {
1686 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1687
1688 if (Canon.isNull()) {
1689 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1690 if (CanonNNS != NNS)
1691 Canon = getTypenameType(CanonNNS, Name);
1692 }
1693
1694 llvm::FoldingSetNodeID ID;
1695 TypenameType::Profile(ID, NNS, Name);
1696
1697 void *InsertPos = 0;
1698 TypenameType *T
1699 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1700 if (T)
1701 return QualType(T, 0);
1702
1703 T = new (*this) TypenameType(NNS, Name, Canon);
1704 Types.push_back(T);
1705 TypenameTypes.InsertNode(T, InsertPos);
1706 return QualType(T, 0);
1707}
1708
Douglas Gregor77da5802009-04-01 00:28:59 +00001709QualType
1710ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1711 const TemplateSpecializationType *TemplateId,
1712 QualType Canon) {
1713 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1714
1715 if (Canon.isNull()) {
1716 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1717 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1718 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1719 const TemplateSpecializationType *CanonTemplateId
1720 = CanonType->getAsTemplateSpecializationType();
1721 assert(CanonTemplateId &&
1722 "Canonical type must also be a template specialization type");
1723 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1724 }
1725 }
1726
1727 llvm::FoldingSetNodeID ID;
1728 TypenameType::Profile(ID, NNS, TemplateId);
1729
1730 void *InsertPos = 0;
1731 TypenameType *T
1732 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1733 if (T)
1734 return QualType(T, 0);
1735
1736 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1737 Types.push_back(T);
1738 TypenameTypes.InsertNode(T, InsertPos);
1739 return QualType(T, 0);
1740}
1741
Chris Lattnere1352302008-04-07 04:56:42 +00001742/// CmpProtocolNames - Comparison predicate for sorting protocols
1743/// alphabetically.
1744static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1745 const ObjCProtocolDecl *RHS) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001746 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere1352302008-04-07 04:56:42 +00001747}
1748
1749static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1750 unsigned &NumProtocols) {
1751 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1752
1753 // Sort protocols, keyed by name.
1754 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1755
1756 // Remove duplicates.
1757 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1758 NumProtocols = ProtocolsEnd-Protocols;
1759}
1760
Steve Naroffc75c1a82009-06-17 22:40:22 +00001761/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1762/// the given interface decl and the conforming protocol list.
Steve Naroff329ec222009-07-10 23:34:53 +00001763QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffc75c1a82009-06-17 22:40:22 +00001764 ObjCProtocolDecl **Protocols,
1765 unsigned NumProtocols) {
1766 // Sort the protocol list alphabetically to canonicalize it.
1767 if (NumProtocols)
1768 SortAndUniqueProtocols(Protocols, NumProtocols);
1769
1770 llvm::FoldingSetNodeID ID;
Steve Naroff329ec222009-07-10 23:34:53 +00001771 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffc75c1a82009-06-17 22:40:22 +00001772
1773 void *InsertPos = 0;
1774 if (ObjCObjectPointerType *QT =
1775 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1776 return QualType(QT, 0);
1777
1778 // No Match;
1779 ObjCObjectPointerType *QType =
Steve Naroff329ec222009-07-10 23:34:53 +00001780 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffc75c1a82009-06-17 22:40:22 +00001781
1782 Types.push_back(QType);
1783 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1784 return QualType(QType, 0);
1785}
Chris Lattnere1352302008-04-07 04:56:42 +00001786
Steve Naroff77763c52009-07-18 15:33:26 +00001787/// getObjCInterfaceType - Return the unique reference to the type for the
1788/// specified ObjC interface decl. The list of protocols is optional.
1789QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek42730c52008-01-07 19:49:32 +00001790 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroff77763c52009-07-18 15:33:26 +00001791 if (NumProtocols)
1792 // Sort the protocol list alphabetically to canonicalize it.
1793 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattnere1352302008-04-07 04:56:42 +00001794
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001795 llvm::FoldingSetNodeID ID;
Steve Naroff77763c52009-07-18 15:33:26 +00001796 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001797
1798 void *InsertPos = 0;
Steve Naroff77763c52009-07-18 15:33:26 +00001799 if (ObjCInterfaceType *QT =
1800 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001801 return QualType(QT, 0);
1802
1803 // No Match;
Steve Naroff77763c52009-07-18 15:33:26 +00001804 ObjCInterfaceType *QType =
1805 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1806 Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001807 Types.push_back(QType);
Steve Naroff77763c52009-07-18 15:33:26 +00001808 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001809 return QualType(QType, 0);
1810}
1811
Douglas Gregor4fa58902009-02-26 23:50:07 +00001812/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1813/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff0604dd92007-08-01 18:02:17 +00001814/// multiple declarations that refer to "typeof(x)" all contain different
1815/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1816/// on canonical type's (which are always unique).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001817QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregord1c0b682009-07-08 00:03:05 +00001818 TypeOfExprType *toe;
1819 if (tofExpr->isTypeDependent())
1820 toe = new (*this, 8) TypeOfExprType(tofExpr);
1821 else {
1822 QualType Canonical = getCanonicalType(tofExpr->getType());
1823 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1824 }
Steve Naroff0604dd92007-08-01 18:02:17 +00001825 Types.push_back(toe);
1826 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001827}
1828
Steve Naroff0604dd92007-08-01 18:02:17 +00001829/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1830/// TypeOfType AST's. The only motivation to unique these nodes would be
1831/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1832/// an issue. This doesn't effect the type checker, since it operates
1833/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +00001834QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001835 QualType Canonical = getCanonicalType(tofType);
Steve Naroff93fd2112009-01-27 22:08:43 +00001836 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001837 Types.push_back(tot);
1838 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001839}
1840
Anders Carlsson09b88962009-06-24 21:24:56 +00001841/// getDecltypeForExpr - Given an expr, will return the decltype for that
1842/// expression, according to the rules in C++0x [dcl.type.simple]p4
1843static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson26dcdbb2009-06-25 15:00:34 +00001844 if (e->isTypeDependent())
1845 return Context.DependentTy;
1846
Anders Carlsson09b88962009-06-24 21:24:56 +00001847 // If e is an id expression or a class member access, decltype(e) is defined
1848 // as the type of the entity named by e.
1849 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1850 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1851 return VD->getType();
1852 }
1853 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1854 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1855 return FD->getType();
1856 }
1857 // If e is a function call or an invocation of an overloaded operator,
1858 // (parentheses around e are ignored), decltype(e) is defined as the
1859 // return type of that function.
1860 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1861 return CE->getCallReturnType();
1862
1863 QualType T = e->getType();
1864
1865 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1866 // defined as T&, otherwise decltype(e) is defined as T.
1867 if (e->isLvalue(Context) == Expr::LV_Valid)
1868 T = Context.getLValueReferenceType(T);
1869
1870 return T;
1871}
1872
Anders Carlsson93ab5332009-06-24 19:06:50 +00001873/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1874/// DecltypeType AST's. The only motivation to unique these nodes would be
1875/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1876/// an issue. This doesn't effect the type checker, since it operates
1877/// on canonical type's (which are always unique).
1878QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregord1c0b682009-07-08 00:03:05 +00001879 DecltypeType *dt;
1880 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson42f394e2009-07-10 19:20:26 +00001881 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregord1c0b682009-07-08 00:03:05 +00001882 else {
1883 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson42f394e2009-07-10 19:20:26 +00001884 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregord1c0b682009-07-08 00:03:05 +00001885 }
Anders Carlsson93ab5332009-06-24 19:06:50 +00001886 Types.push_back(dt);
1887 return QualType(dt, 0);
1888}
1889
Chris Lattner4b009652007-07-25 00:24:17 +00001890/// getTagDeclType - Return the unique reference to the type for the
1891/// specified TagDecl (struct/union/class/enum) decl.
1892QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +00001893 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +00001894 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001895}
1896
1897/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1898/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1899/// needs to agree with the definition in <stddef.h>.
1900QualType ASTContext::getSizeType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001901 return getFromTargetType(Target.getSizeType());
Chris Lattner4b009652007-07-25 00:24:17 +00001902}
1903
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001904/// getSignedWCharType - Return the type of "signed wchar_t".
1905/// Used when in C++, as a GCC extension.
1906QualType ASTContext::getSignedWCharType() const {
1907 // FIXME: derive from "Target" ?
1908 return WCharTy;
1909}
1910
1911/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1912/// Used when in C++, as a GCC extension.
1913QualType ASTContext::getUnsignedWCharType() const {
1914 // FIXME: derive from "Target" ?
1915 return UnsignedIntTy;
1916}
1917
Chris Lattner4b009652007-07-25 00:24:17 +00001918/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1919/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1920QualType ASTContext::getPointerDiffType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001921 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner4b009652007-07-25 00:24:17 +00001922}
1923
Chris Lattner19eb97e2008-04-02 05:18:44 +00001924//===----------------------------------------------------------------------===//
1925// Type Operators
1926//===----------------------------------------------------------------------===//
1927
Chris Lattner3dae6f42008-04-06 22:41:35 +00001928/// getCanonicalType - Return the canonical (structural) type corresponding to
1929/// the specified potentially non-canonical type. The non-canonical version
1930/// of a type may have many "decorated" versions of types. Decorators can
1931/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1932/// to be free of any of these, allowing two canonical types to be compared
1933/// for exact equality with a simple pointer comparison.
1934QualType ASTContext::getCanonicalType(QualType T) {
1935 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001936
1937 // If the result has type qualifiers, make sure to canonicalize them as well.
1938 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1939 if (TypeQuals == 0) return CanType;
1940
1941 // If the type qualifiers are on an array type, get the canonical type of the
1942 // array with the qualifiers applied to the element type.
1943 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1944 if (!AT)
1945 return CanType.getQualifiedType(TypeQuals);
1946
1947 // Get the canonical version of the element with the extra qualifiers on it.
1948 // This can recursively sink qualifiers through multiple levels of arrays.
1949 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1950 NewEltTy = getCanonicalType(NewEltTy);
1951
1952 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1953 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1954 CAT->getIndexTypeQualifier());
1955 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1956 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1957 IAT->getIndexTypeQualifier());
1958
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001959 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor1d381132009-07-06 15:59:29 +00001960 return getDependentSizedArrayType(NewEltTy,
1961 DSAT->getSizeExpr(),
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001962 DSAT->getSizeModifier(),
Douglas Gregor1d381132009-07-06 15:59:29 +00001963 DSAT->getIndexTypeQualifier(),
1964 DSAT->getBracketsRange());
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001965
Chris Lattnera1923f62008-08-04 07:31:14 +00001966 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor1d381132009-07-06 15:59:29 +00001967 return getVariableArrayType(NewEltTy,
1968 VAT->getSizeExpr(),
Chris Lattnera1923f62008-08-04 07:31:14 +00001969 VAT->getSizeModifier(),
Douglas Gregor1d381132009-07-06 15:59:29 +00001970 VAT->getIndexTypeQualifier(),
1971 VAT->getBracketsRange());
Chris Lattnera1923f62008-08-04 07:31:14 +00001972}
1973
Douglas Gregorb88ba412009-05-07 06:41:52 +00001974TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1975 // If this template name refers to a template, the canonical
1976 // template name merely stores the template itself.
1977 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001978 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregorb88ba412009-05-07 06:41:52 +00001979
1980 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1981 assert(DTN && "Non-dependent template names must refer to template decls.");
1982 return DTN->CanonicalTemplateName;
1983}
1984
Douglas Gregord3022602009-03-27 23:10:48 +00001985NestedNameSpecifier *
1986ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1987 if (!NNS)
1988 return 0;
1989
1990 switch (NNS->getKind()) {
1991 case NestedNameSpecifier::Identifier:
1992 // Canonicalize the prefix but keep the identifier the same.
1993 return NestedNameSpecifier::Create(*this,
1994 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1995 NNS->getAsIdentifier());
1996
1997 case NestedNameSpecifier::Namespace:
1998 // A namespace is canonical; build a nested-name-specifier with
1999 // this namespace and no prefix.
2000 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2001
2002 case NestedNameSpecifier::TypeSpec:
2003 case NestedNameSpecifier::TypeSpecWithTemplate: {
2004 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2005 NestedNameSpecifier *Prefix = 0;
2006
2007 // FIXME: This isn't the right check!
2008 if (T->isDependentType())
2009 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2010
2011 return NestedNameSpecifier::Create(*this, Prefix,
2012 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2013 T.getTypePtr());
2014 }
2015
2016 case NestedNameSpecifier::Global:
2017 // The global specifier is canonical and unique.
2018 return NNS;
2019 }
2020
2021 // Required to silence a GCC warning
2022 return 0;
2023}
2024
Chris Lattnera1923f62008-08-04 07:31:14 +00002025
2026const ArrayType *ASTContext::getAsArrayType(QualType T) {
2027 // Handle the non-qualified case efficiently.
2028 if (T.getCVRQualifiers() == 0) {
2029 // Handle the common positive case fast.
2030 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2031 return AT;
2032 }
2033
2034 // Handle the common negative case fast, ignoring CVR qualifiers.
2035 QualType CType = T->getCanonicalTypeInternal();
2036
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002037 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnera1923f62008-08-04 07:31:14 +00002038 // test.
2039 if (!isa<ArrayType>(CType) &&
2040 !isa<ArrayType>(CType.getUnqualifiedType()))
2041 return 0;
2042
2043 // Apply any CVR qualifiers from the array type to the element type. This
2044 // implements C99 6.7.3p8: "If the specification of an array type includes
2045 // any type qualifiers, the element type is so qualified, not the array type."
2046
2047 // If we get here, we either have type qualifiers on the type, or we have
2048 // sugar such as a typedef in the way. If we have type qualifiers on the type
2049 // we must propagate them down into the elemeng type.
2050 unsigned CVRQuals = T.getCVRQualifiers();
2051 unsigned AddrSpace = 0;
2052 Type *Ty = T.getTypePtr();
2053
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002054 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnera1923f62008-08-04 07:31:14 +00002055 while (1) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002056 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2057 AddrSpace = EXTQT->getAddressSpace();
2058 Ty = EXTQT->getBaseType();
Chris Lattnera1923f62008-08-04 07:31:14 +00002059 } else {
2060 T = Ty->getDesugaredType();
2061 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2062 break;
2063 CVRQuals |= T.getCVRQualifiers();
2064 Ty = T.getTypePtr();
2065 }
2066 }
2067
2068 // If we have a simple case, just return now.
2069 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2070 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2071 return ATy;
2072
2073 // Otherwise, we have an array and we have qualifiers on it. Push the
2074 // qualifiers into the array element type and return a new array type.
2075 // Get the canonical version of the element with the extra qualifiers on it.
2076 // This can recursively sink qualifiers through multiple levels of arrays.
2077 QualType NewEltTy = ATy->getElementType();
2078 if (AddrSpace)
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002079 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnera1923f62008-08-04 07:31:14 +00002080 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2081
2082 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2083 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2084 CAT->getSizeModifier(),
2085 CAT->getIndexTypeQualifier()));
2086 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2087 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2088 IAT->getSizeModifier(),
Douglas Gregor1d381132009-07-06 15:59:29 +00002089 IAT->getIndexTypeQualifier()));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002090
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002091 if (const DependentSizedArrayType *DSAT
2092 = dyn_cast<DependentSizedArrayType>(ATy))
2093 return cast<ArrayType>(
2094 getDependentSizedArrayType(NewEltTy,
2095 DSAT->getSizeExpr(),
2096 DSAT->getSizeModifier(),
Douglas Gregor1d381132009-07-06 15:59:29 +00002097 DSAT->getIndexTypeQualifier(),
2098 DSAT->getBracketsRange()));
Chris Lattnera1923f62008-08-04 07:31:14 +00002099
Chris Lattnera1923f62008-08-04 07:31:14 +00002100 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor1d381132009-07-06 15:59:29 +00002101 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2102 VAT->getSizeExpr(),
Chris Lattnera1923f62008-08-04 07:31:14 +00002103 VAT->getSizeModifier(),
Douglas Gregor1d381132009-07-06 15:59:29 +00002104 VAT->getIndexTypeQualifier(),
2105 VAT->getBracketsRange()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00002106}
2107
2108
Chris Lattner19eb97e2008-04-02 05:18:44 +00002109/// getArrayDecayedType - Return the properly qualified result of decaying the
2110/// specified array type to a pointer. This operation is non-trivial when
2111/// handling typedefs etc. The canonical type of "T" must be an array type,
2112/// this returns a pointer to a properly qualified element of the array.
2113///
2114/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2115QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002116 // Get the element type with 'getAsArrayType' so that we don't lose any
2117 // typedefs in the element type of the array. This also handles propagation
2118 // of type qualifiers from the array type into the element type if present
2119 // (C99 6.7.3p8).
2120 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2121 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00002122
Chris Lattnera1923f62008-08-04 07:31:14 +00002123 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00002124
2125 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00002126 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00002127}
2128
Douglas Gregor4af05232009-07-23 23:49:00 +00002129QualType ASTContext::getBaseElementType(QualType QT) {
2130 QualifierSet qualifiers;
2131 while (true) {
2132 const Type *UT = qualifiers.strip(QT);
2133 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2134 QT = AT->getElementType();
2135 }else {
2136 return qualifiers.apply(QT, *this);
2137 }
2138 }
2139}
2140
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00002141QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson76d19c82008-12-21 03:44:36 +00002142 QualType ElemTy = VAT->getElementType();
2143
2144 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2145 return getBaseElementType(VAT);
2146
2147 return ElemTy;
2148}
2149
Chris Lattner4b009652007-07-25 00:24:17 +00002150/// getFloatingRank - Return a relative rank for floating point types.
2151/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00002152static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002153 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00002154 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00002155
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00002156 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lamb2a72bb32008-02-04 02:31:56 +00002157 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00002158 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00002159 case BuiltinType::Float: return FloatRank;
2160 case BuiltinType::Double: return DoubleRank;
2161 case BuiltinType::LongDouble: return LongDoubleRank;
2162 }
2163}
2164
Steve Narofffa0c4532007-08-27 01:41:48 +00002165/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2166/// point or a complex type (based on typeDomain/typeSize).
2167/// 'typeDomain' is a real floating point or complex type.
2168/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00002169QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2170 QualType Domain) const {
2171 FloatingRank EltRank = getFloatingRank(Size);
2172 if (Domain->isComplexType()) {
2173 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00002174 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00002175 case FloatRank: return FloatComplexTy;
2176 case DoubleRank: return DoubleComplexTy;
2177 case LongDoubleRank: return LongDoubleComplexTy;
2178 }
Chris Lattner4b009652007-07-25 00:24:17 +00002179 }
Chris Lattner7794ae22008-04-06 23:58:54 +00002180
2181 assert(Domain->isRealFloatingType() && "Unknown domain!");
2182 switch (EltRank) {
2183 default: assert(0 && "getFloatingRank(): illegal value for rank");
2184 case FloatRank: return FloatTy;
2185 case DoubleRank: return DoubleTy;
2186 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00002187 }
Chris Lattner4b009652007-07-25 00:24:17 +00002188}
2189
Chris Lattner51285d82008-04-06 23:55:33 +00002190/// getFloatingTypeOrder - Compare the rank of the two specified floating
2191/// point types, ignoring the domain of the type (i.e. 'double' ==
2192/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2193/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00002194int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2195 FloatingRank LHSR = getFloatingRank(LHS);
2196 FloatingRank RHSR = getFloatingRank(RHS);
2197
2198 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00002199 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00002200 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00002201 return 1;
2202 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00002203}
2204
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002205/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2206/// routine will assert if passed a built-in type that isn't an integer or enum,
2207/// or if it is not canonicalized.
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002208unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002209 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002210 if (EnumType* ET = dyn_cast<EnumType>(T))
2211 T = ET->getDecl()->getIntegerType().getTypePtr();
2212
Eli Friedman78c50f12009-07-05 23:44:27 +00002213 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2214 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2215
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002216 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2217 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2218
2219 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2220 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2221
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002222 // There are two things which impact the integer rank: the width, and
2223 // the ordering of builtins. The builtin ordering is encoded in the
2224 // bottom three bits; the width is encoded in the bits above that.
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002225 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002226 return FWIT->getWidth() << 3;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002227
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002228 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00002229 default: assert(0 && "getIntegerRank(): not a built-in integer");
2230 case BuiltinType::Bool:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002231 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002232 case BuiltinType::Char_S:
2233 case BuiltinType::Char_U:
2234 case BuiltinType::SChar:
2235 case BuiltinType::UChar:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002236 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002237 case BuiltinType::Short:
2238 case BuiltinType::UShort:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002239 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002240 case BuiltinType::Int:
2241 case BuiltinType::UInt:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002242 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002243 case BuiltinType::Long:
2244 case BuiltinType::ULong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002245 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002246 case BuiltinType::LongLong:
2247 case BuiltinType::ULongLong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002248 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner6cc7e412009-04-30 02:43:43 +00002249 case BuiltinType::Int128:
2250 case BuiltinType::UInt128:
2251 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002252 }
2253}
2254
Chris Lattner51285d82008-04-06 23:55:33 +00002255/// getIntegerTypeOrder - Returns the highest ranked integer type:
2256/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2257/// LHS < RHS, return -1.
2258int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002259 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2260 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00002261 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002262
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002263 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2264 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00002265
Chris Lattner51285d82008-04-06 23:55:33 +00002266 unsigned LHSRank = getIntegerRank(LHSC);
2267 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00002268
Chris Lattner51285d82008-04-06 23:55:33 +00002269 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2270 if (LHSRank == RHSRank) return 0;
2271 return LHSRank > RHSRank ? 1 : -1;
2272 }
Chris Lattner4b009652007-07-25 00:24:17 +00002273
Chris Lattner51285d82008-04-06 23:55:33 +00002274 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2275 if (LHSUnsigned) {
2276 // If the unsigned [LHS] type is larger, return it.
2277 if (LHSRank >= RHSRank)
2278 return 1;
2279
2280 // If the signed type can represent all values of the unsigned type, it
2281 // wins. Because we are dealing with 2's complement and types that are
2282 // powers of two larger than each other, this is always safe.
2283 return -1;
2284 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002285
Chris Lattner51285d82008-04-06 23:55:33 +00002286 // If the unsigned [RHS] type is larger, return it.
2287 if (RHSRank >= LHSRank)
2288 return -1;
2289
2290 // If the signed type can represent all values of the unsigned type, it
2291 // wins. Because we are dealing with 2's complement and types that are
2292 // powers of two larger than each other, this is always safe.
2293 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00002294}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002295
2296// getCFConstantStringType - Return the type used for constant CFStrings.
2297QualType ASTContext::getCFConstantStringType() {
2298 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00002299 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002300 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002301 &Idents.get("NSConstantString"));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002302 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002303
2304 // const int *isa;
2305 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002306 // int flags;
2307 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002308 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002309 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002310 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002311 FieldTypes[3] = LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002312
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002313 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002314 for (unsigned i = 0; i < 4; ++i) {
2315 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2316 SourceLocation(), 0,
2317 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002318 /*Mutable=*/false);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002319 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002320 }
2321
2322 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002323 }
2324
2325 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00002326}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002327
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002328void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002329 const RecordType *Rec = T->getAsRecordType();
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002330 assert(Rec && "Invalid CFConstantStringType");
2331 CFConstantStringTypeDecl = Rec->getDecl();
2332}
2333
Anders Carlssonf58cac72008-08-30 19:34:46 +00002334QualType ASTContext::getObjCFastEnumerationStateType()
2335{
2336 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00002337 ObjCFastEnumerationStateTypeDecl =
2338 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2339 &Idents.get("__objcFastEnumerationState"));
2340
Anders Carlssonf58cac72008-08-30 19:34:46 +00002341 QualType FieldTypes[] = {
2342 UnsignedLongTy,
Steve Naroff7bffd372009-07-15 18:40:39 +00002343 getPointerType(ObjCIdTypedefType),
Anders Carlssonf58cac72008-08-30 19:34:46 +00002344 getPointerType(UnsignedLongTy),
2345 getConstantArrayType(UnsignedLongTy,
2346 llvm::APInt(32, 5), ArrayType::Normal, 0)
2347 };
2348
Douglas Gregor8acb7272008-12-11 16:49:14 +00002349 for (size_t i = 0; i < 4; ++i) {
2350 FieldDecl *Field = FieldDecl::Create(*this,
2351 ObjCFastEnumerationStateTypeDecl,
2352 SourceLocation(), 0,
2353 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002354 /*Mutable=*/false);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002355 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002356 }
Anders Carlssonf58cac72008-08-30 19:34:46 +00002357
Douglas Gregor8acb7272008-12-11 16:49:14 +00002358 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonf58cac72008-08-30 19:34:46 +00002359 }
2360
2361 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2362}
2363
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002364void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002365 const RecordType *Rec = T->getAsRecordType();
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002366 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2367 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2368}
2369
Anders Carlssone3f02572007-10-29 06:33:42 +00002370// This returns true if a type has been typedefed to BOOL:
2371// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00002372static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00002373 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner85fb3842008-11-24 03:52:59 +00002374 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2375 return II->isStr("BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002376
2377 return false;
2378}
2379
Ted Kremenek42730c52008-01-07 19:49:32 +00002380/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002381/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00002382int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002383 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002384
2385 // Make all integer and enum types at least as large as an int
2386 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002387 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002388 // Treat arrays as pointers, since that's how they're passed in.
2389 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002390 sz = getTypeSize(VoidPtrTy);
2391 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002392}
2393
Ted Kremenek42730c52008-01-07 19:49:32 +00002394/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002395/// declaration.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002396void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnerae430292008-11-19 07:24:05 +00002397 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002398 // FIXME: This is not very efficient.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002399 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00002400 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002401 // Encode result type.
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002402 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002403 // Compute size of all parameters.
2404 // Start with computing size of a pointer in number of bytes.
2405 // FIXME: There might(should) be a better way of doing this computation!
2406 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002407 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002408 // The first two arguments (self and _cmd) are pointers; account for
2409 // their size.
2410 int ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002411 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2412 E = Decl->param_end(); PI != E; ++PI) {
2413 QualType PType = (*PI)->getType();
2414 int sz = getObjCEncodingTypeSize(PType);
Ted Kremenek42730c52008-01-07 19:49:32 +00002415 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002416 ParmOffset += sz;
2417 }
2418 S += llvm::utostr(ParmOffset);
2419 S += "@0:";
2420 S += llvm::utostr(PtrSize);
2421
2422 // Argument types.
2423 ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002424 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2425 E = Decl->param_end(); PI != E; ++PI) {
2426 ParmVarDecl *PVDecl = *PI;
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002427 QualType PType = PVDecl->getOriginalType();
2428 if (const ArrayType *AT =
Steve Naroff78380fb2009-04-14 00:03:58 +00002429 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2430 // Use array's original type only if it has known number of
2431 // elements.
Steve Naroff6777bf32009-04-14 00:40:09 +00002432 if (!isa<ConstantArrayType>(AT))
Steve Naroff78380fb2009-04-14 00:03:58 +00002433 PType = PVDecl->getType();
2434 } else if (PType->isFunctionType())
2435 PType = PVDecl->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002436 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002437 // 'in', 'inout', etc.
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002438 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002439 getObjCEncodingForType(PType, S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002440 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00002441 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002442 }
2443}
2444
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002445/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002446/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002447/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2448/// NULL when getting encodings for protocol properties.
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002449/// Property attributes are stored as a comma-delimited C string. The simple
2450/// attributes readonly and bycopy are encoded as single characters. The
2451/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2452/// encoded as single characters, followed by an identifier. Property types
2453/// are also encoded as a parametrized attribute. The characters used to encode
2454/// these attributes are defined by the following enumeration:
2455/// @code
2456/// enum PropertyAttributes {
2457/// kPropertyReadOnly = 'R', // property is read-only.
2458/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2459/// kPropertyByref = '&', // property is a reference to the value last assigned
2460/// kPropertyDynamic = 'D', // property is dynamic
2461/// kPropertyGetter = 'G', // followed by getter selector name
2462/// kPropertySetter = 'S', // followed by setter selector name
2463/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2464/// kPropertyType = 't' // followed by old-style type encoding.
2465/// kPropertyWeak = 'W' // 'weak' property
2466/// kPropertyStrong = 'P' // property GC'able
2467/// kPropertyNonAtomic = 'N' // property non-atomic
2468/// };
2469/// @endcode
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002470void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2471 const Decl *Container,
Chris Lattnerae430292008-11-19 07:24:05 +00002472 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002473 // Collect information from the property implementation decl(s).
2474 bool Dynamic = false;
2475 ObjCPropertyImplDecl *SynthesizePID = 0;
2476
2477 // FIXME: Duplicated code due to poor abstraction.
2478 if (Container) {
2479 if (const ObjCCategoryImplDecl *CID =
2480 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2481 for (ObjCCategoryImplDecl::propimpl_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002482 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00002483 i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002484 ObjCPropertyImplDecl *PID = *i;
2485 if (PID->getPropertyDecl() == PD) {
2486 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2487 Dynamic = true;
2488 } else {
2489 SynthesizePID = PID;
2490 }
2491 }
2492 }
2493 } else {
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002494 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002495 for (ObjCCategoryImplDecl::propimpl_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002496 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00002497 i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002498 ObjCPropertyImplDecl *PID = *i;
2499 if (PID->getPropertyDecl() == PD) {
2500 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2501 Dynamic = true;
2502 } else {
2503 SynthesizePID = PID;
2504 }
2505 }
2506 }
2507 }
2508 }
2509
2510 // FIXME: This is not very efficient.
2511 S = "T";
2512
2513 // Encode result type.
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002514 // GCC has some special rules regarding encoding of properties which
2515 // closely resembles encoding of ivars.
Daniel Dunbar701c8502009-04-20 06:37:24 +00002516 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002517 true /* outermost type */,
2518 true /* encoding for property */);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002519
2520 if (PD->isReadOnly()) {
2521 S += ",R";
2522 } else {
2523 switch (PD->getSetterKind()) {
2524 case ObjCPropertyDecl::Assign: break;
2525 case ObjCPropertyDecl::Copy: S += ",C"; break;
2526 case ObjCPropertyDecl::Retain: S += ",&"; break;
2527 }
2528 }
2529
2530 // It really isn't clear at all what this means, since properties
2531 // are "dynamic by default".
2532 if (Dynamic)
2533 S += ",D";
2534
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002535 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2536 S += ",N";
2537
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002538 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2539 S += ",G";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002540 S += PD->getGetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002541 }
2542
2543 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2544 S += ",S";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002545 S += PD->getSetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002546 }
2547
2548 if (SynthesizePID) {
2549 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2550 S += ",V";
Chris Lattner6c5ec622008-11-24 04:00:27 +00002551 S += OID->getNameAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002552 }
2553
2554 // FIXME: OBJCGC: weak & strong
2555}
2556
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002557/// getLegacyIntegralTypeEncoding -
2558/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanian89155952009-02-11 23:59:18 +00002559/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002560/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2561///
2562void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump6eeaa782009-07-22 18:58:19 +00002563 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002564 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanian89155952009-02-11 23:59:18 +00002565 if (BT->getKind() == BuiltinType::ULong &&
2566 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002567 PointeeTy = UnsignedIntTy;
Fariborz Jahanian89155952009-02-11 23:59:18 +00002568 else
2569 if (BT->getKind() == BuiltinType::Long &&
2570 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002571 PointeeTy = IntTy;
2572 }
2573 }
2574}
2575
Fariborz Jahanian248db262008-01-22 22:44:46 +00002576void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002577 const FieldDecl *Field) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002578 // We follow the behavior of gcc, expanding structures which are
2579 // directly pointed to, and expanding embedded structures. Note that
2580 // these rules are sufficient to prevent recursive encoding of the
2581 // same type.
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002582 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2583 true /* outermost type */);
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002584}
2585
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002586static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002587 const FieldDecl *FD) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002588 const Expr *E = FD->getBitWidth();
2589 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2590 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman5255e7a2009-04-26 19:19:15 +00002591 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002592 S += 'b';
2593 S += llvm::utostr(N);
2594}
2595
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002596void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2597 bool ExpandPointedToStructures,
2598 bool ExpandStructures,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002599 const FieldDecl *FD,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002600 bool OutermostType,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002601 bool EncodingProperty) {
Anders Carlssone3f02572007-10-29 06:33:42 +00002602 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattner26e73852009-07-13 00:10:46 +00002603 if (FD && FD->isBitField())
2604 return EncodeBitField(this, S, FD);
2605 char encoding;
2606 switch (BT->getKind()) {
2607 default: assert(0 && "Unhandled builtin type kind");
2608 case BuiltinType::Void: encoding = 'v'; break;
2609 case BuiltinType::Bool: encoding = 'B'; break;
2610 case BuiltinType::Char_U:
2611 case BuiltinType::UChar: encoding = 'C'; break;
2612 case BuiltinType::UShort: encoding = 'S'; break;
2613 case BuiltinType::UInt: encoding = 'I'; break;
2614 case BuiltinType::ULong:
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002615 encoding =
Chris Lattner26e73852009-07-13 00:10:46 +00002616 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002617 break;
Chris Lattner26e73852009-07-13 00:10:46 +00002618 case BuiltinType::UInt128: encoding = 'T'; break;
2619 case BuiltinType::ULongLong: encoding = 'Q'; break;
2620 case BuiltinType::Char_S:
2621 case BuiltinType::SChar: encoding = 'c'; break;
2622 case BuiltinType::Short: encoding = 's'; break;
2623 case BuiltinType::Int: encoding = 'i'; break;
2624 case BuiltinType::Long:
2625 encoding =
2626 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2627 break;
2628 case BuiltinType::LongLong: encoding = 'q'; break;
2629 case BuiltinType::Int128: encoding = 't'; break;
2630 case BuiltinType::Float: encoding = 'f'; break;
2631 case BuiltinType::Double: encoding = 'd'; break;
2632 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002633 }
Chris Lattner26e73852009-07-13 00:10:46 +00002634
2635 S += encoding;
2636 return;
2637 }
2638
2639 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlsson70e16dd2009-04-09 21:55:45 +00002640 S += 'j';
2641 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2642 false);
Chris Lattner26e73852009-07-13 00:10:46 +00002643 return;
2644 }
2645
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002646 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002647 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002648 bool isReadOnly = false;
2649 // For historical/compatibility reasons, the read-only qualifier of the
2650 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2651 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2652 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump6eeaa782009-07-22 18:58:19 +00002653 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002654 if (OutermostType && T.isConstQualified()) {
2655 isReadOnly = true;
2656 S += 'r';
2657 }
2658 }
2659 else if (OutermostType) {
2660 QualType P = PointeeTy;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002661 while (P->getAsPointerType())
2662 P = P->getAsPointerType()->getPointeeType();
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002663 if (P.isConstQualified()) {
2664 isReadOnly = true;
2665 S += 'r';
2666 }
2667 }
2668 if (isReadOnly) {
2669 // Another legacy compatibility encoding. Some ObjC qualifier and type
2670 // combinations need to be rearranged.
2671 // Rewrite "in const" from "nr" to "rn"
2672 const char * s = S.c_str();
2673 int len = S.length();
2674 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2675 std::string replace = "rn";
2676 S.replace(S.end()-2, S.end(), replace);
2677 }
2678 }
Steve Naroff329ec222009-07-10 23:34:53 +00002679 if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002680 S += ':';
2681 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002682 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002683
2684 if (PointeeTy->isCharType()) {
2685 // char pointer types should be encoded as '*' unless it is a
2686 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00002687 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002688 S += '*';
2689 return;
2690 }
Steve Naroff0b60cf82009-07-22 17:14:51 +00002691 } else if (const RecordType *RTy = PointeeTy->getAsRecordType()) {
2692 // GCC binary compat: Need to convert "struct objc_class *" to "#".
2693 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2694 S += '#';
2695 return;
2696 }
2697 // GCC binary compat: Need to convert "struct objc_object *" to "@".
2698 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2699 S += '@';
2700 return;
2701 }
2702 // fall through...
Anders Carlsson36f07d82007-10-29 05:01:08 +00002703 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002704 S += '^';
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002705 getLegacyIntegralTypeEncoding(PointeeTy);
2706
Chris Lattner26e73852009-07-13 00:10:46 +00002707 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002708 NULL);
Chris Lattner26e73852009-07-13 00:10:46 +00002709 return;
2710 }
2711
2712 if (const ArrayType *AT =
2713 // Ignore type qualifiers etc.
2714 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson858c64d2009-02-22 01:38:57 +00002715 if (isa<IncompleteArrayType>(AT)) {
2716 // Incomplete arrays are encoded as a pointer to the array element.
2717 S += '^';
2718
2719 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2720 false, ExpandStructures, FD);
2721 } else {
2722 S += '[';
Anders Carlsson36f07d82007-10-29 05:01:08 +00002723
Anders Carlsson858c64d2009-02-22 01:38:57 +00002724 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2725 S += llvm::utostr(CAT->getSize().getZExtValue());
2726 else {
2727 //Variable length arrays are encoded as a regular array with 0 elements.
2728 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2729 S += '0';
2730 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002731
Anders Carlsson858c64d2009-02-22 01:38:57 +00002732 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2733 false, ExpandStructures, FD);
2734 S += ']';
2735 }
Chris Lattner26e73852009-07-13 00:10:46 +00002736 return;
2737 }
2738
2739 if (T->getAsFunctionType()) {
Anders Carlsson5695bb72007-10-30 00:06:20 +00002740 S += '?';
Chris Lattner26e73852009-07-13 00:10:46 +00002741 return;
2742 }
2743
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002744 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002745 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002746 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar146b2d02008-10-17 06:22:57 +00002747 // Anonymous structures print as '?'
2748 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2749 S += II->getName();
2750 } else {
2751 S += '?';
2752 }
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002753 if (ExpandStructures) {
Fariborz Jahanian248db262008-01-22 22:44:46 +00002754 S += '=';
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002755 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2756 FieldEnd = RDecl->field_end();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002757 Field != FieldEnd; ++Field) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002758 if (FD) {
Daniel Dunbaraa913102008-10-17 16:17:37 +00002759 S += '"';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002760 S += Field->getNameAsString();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002761 S += '"';
2762 }
2763
2764 // Special case bit-fields.
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002765 if (Field->isBitField()) {
2766 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2767 (*Field));
Daniel Dunbaraa913102008-10-17 16:17:37 +00002768 } else {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002769 QualType qt = Field->getType();
2770 getLegacyIntegralTypeEncoding(qt);
2771 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002772 FD);
Daniel Dunbaraa913102008-10-17 16:17:37 +00002773 }
Fariborz Jahanian248db262008-01-22 22:44:46 +00002774 }
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002775 }
Daniel Dunbaraa913102008-10-17 16:17:37 +00002776 S += RDecl->isUnion() ? ')' : '}';
Chris Lattner26e73852009-07-13 00:10:46 +00002777 return;
2778 }
2779
2780 if (T->isEnumeralType()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002781 if (FD && FD->isBitField())
2782 EncodeBitField(this, S, FD);
2783 else
2784 S += 'i';
Chris Lattner26e73852009-07-13 00:10:46 +00002785 return;
2786 }
2787
2788 if (T->isBlockPointerType()) {
Steve Naroff725e0662009-02-02 18:24:29 +00002789 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattner26e73852009-07-13 00:10:46 +00002790 return;
2791 }
2792
2793 if (T->isObjCInterfaceType()) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002794 // @encode(class_name)
2795 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2796 S += '{';
2797 const IdentifierInfo *II = OI->getIdentifier();
2798 S += II->getName();
2799 S += '=';
Chris Lattner9329cf52009-03-31 08:48:01 +00002800 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002801 CollectObjCIvars(OI, RecFields);
Chris Lattner9329cf52009-03-31 08:48:01 +00002802 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002803 if (RecFields[i]->isBitField())
2804 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2805 RecFields[i]);
2806 else
2807 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2808 FD);
2809 }
2810 S += '}';
Chris Lattner26e73852009-07-13 00:10:46 +00002811 return;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002812 }
Chris Lattner26e73852009-07-13 00:10:46 +00002813
2814 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002815 if (OPT->isObjCIdType()) {
2816 S += '@';
2817 return;
Chris Lattner26e73852009-07-13 00:10:46 +00002818 }
2819
2820 if (OPT->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002821 S += '#';
2822 return;
Chris Lattner26e73852009-07-13 00:10:46 +00002823 }
2824
2825 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002826 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2827 ExpandPointedToStructures,
2828 ExpandStructures, FD);
2829 if (FD || EncodingProperty) {
2830 // Note that we do extended encoding of protocol qualifer list
2831 // Only when doing ivar or property encoding.
Steve Naroff329ec222009-07-10 23:34:53 +00002832 S += '"';
Steve Naroff8194a542009-07-20 17:56:53 +00002833 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2834 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff329ec222009-07-10 23:34:53 +00002835 S += '<';
2836 S += (*I)->getNameAsString();
2837 S += '>';
2838 }
2839 S += '"';
2840 }
2841 return;
Chris Lattner26e73852009-07-13 00:10:46 +00002842 }
2843
2844 QualType PointeeTy = OPT->getPointeeType();
2845 if (!EncodingProperty &&
2846 isa<TypedefType>(PointeeTy.getTypePtr())) {
2847 // Another historical/compatibility reason.
2848 // We encode the underlying type which comes out as
2849 // {...};
2850 S += '^';
2851 getObjCEncodingForTypeImpl(PointeeTy, S,
2852 false, ExpandPointedToStructures,
2853 NULL);
Steve Naroff329ec222009-07-10 23:34:53 +00002854 return;
2855 }
Chris Lattner26e73852009-07-13 00:10:46 +00002856
2857 S += '@';
2858 if (FD || EncodingProperty) {
Chris Lattner26e73852009-07-13 00:10:46 +00002859 S += '"';
Steve Naroff8194a542009-07-20 17:56:53 +00002860 S += OPT->getInterfaceDecl()->getNameAsCString();
2861 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2862 E = OPT->qual_end(); I != E; ++I) {
Chris Lattner26e73852009-07-13 00:10:46 +00002863 S += '<';
2864 S += (*I)->getNameAsString();
2865 S += '>';
2866 }
2867 S += '"';
2868 }
2869 return;
2870 }
2871
2872 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002873}
2874
Ted Kremenek42730c52008-01-07 19:49:32 +00002875void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002876 std::string& S) const {
2877 if (QT & Decl::OBJC_TQ_In)
2878 S += 'n';
2879 if (QT & Decl::OBJC_TQ_Inout)
2880 S += 'N';
2881 if (QT & Decl::OBJC_TQ_Out)
2882 S += 'o';
2883 if (QT & Decl::OBJC_TQ_Bycopy)
2884 S += 'O';
2885 if (QT & Decl::OBJC_TQ_Byref)
2886 S += 'R';
2887 if (QT & Decl::OBJC_TQ_Oneway)
2888 S += 'V';
2889}
2890
Chris Lattner26e73852009-07-13 00:10:46 +00002891void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002892 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2893
2894 BuiltinVaListType = T;
2895}
2896
Chris Lattner26e73852009-07-13 00:10:46 +00002897void ASTContext::setObjCIdType(QualType T) {
Steve Naroff7bffd372009-07-15 18:40:39 +00002898 ObjCIdTypedefType = T;
Steve Naroff9d12c902007-10-15 14:41:52 +00002899}
2900
Chris Lattner26e73852009-07-13 00:10:46 +00002901void ASTContext::setObjCSelType(QualType T) {
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002902 ObjCSelType = T;
2903
2904 const TypedefType *TT = T->getAsTypedefType();
2905 if (!TT)
2906 return;
2907 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002908
2909 // typedef struct objc_selector *SEL;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002910 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002911 if (!ptr)
2912 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002913 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002914 if (!rec)
2915 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002916 SelStructType = rec;
2917}
2918
Chris Lattner26e73852009-07-13 00:10:46 +00002919void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002920 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002921}
2922
Chris Lattner26e73852009-07-13 00:10:46 +00002923void ASTContext::setObjCClassType(QualType T) {
Steve Naroff7bffd372009-07-15 18:40:39 +00002924 ObjCClassTypedefType = T;
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002925}
2926
Ted Kremenek42730c52008-01-07 19:49:32 +00002927void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2928 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00002929 "'NSConstantString' type already set!");
2930
Ted Kremenek42730c52008-01-07 19:49:32 +00002931 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00002932}
2933
Douglas Gregordd13e842009-03-30 22:58:21 +00002934/// \brief Retrieve the template name that represents a qualified
2935/// template name such as \c std::vector.
2936TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2937 bool TemplateKeyword,
2938 TemplateDecl *Template) {
2939 llvm::FoldingSetNodeID ID;
2940 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2941
2942 void *InsertPos = 0;
2943 QualifiedTemplateName *QTN =
2944 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2945 if (!QTN) {
2946 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2947 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2948 }
2949
2950 return TemplateName(QTN);
2951}
2952
2953/// \brief Retrieve the template name that represents a dependent
2954/// template name such as \c MetaFun::template apply.
2955TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2956 const IdentifierInfo *Name) {
2957 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2958
2959 llvm::FoldingSetNodeID ID;
2960 DependentTemplateName::Profile(ID, NNS, Name);
2961
2962 void *InsertPos = 0;
2963 DependentTemplateName *QTN =
2964 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2965
2966 if (QTN)
2967 return TemplateName(QTN);
2968
2969 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2970 if (CanonNNS == NNS) {
2971 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2972 } else {
2973 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2974 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2975 }
2976
2977 DependentTemplateNames.InsertNode(QTN, InsertPos);
2978 return TemplateName(QTN);
2979}
2980
Douglas Gregorc6507e42008-11-03 14:12:49 +00002981/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorbb66b412008-11-03 15:57:00 +00002982/// TargetInfo, produce the corresponding type. The unsigned @p Type
2983/// is actually a value of type @c TargetInfo::IntType.
2984QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00002985 switch (Type) {
2986 case TargetInfo::NoInt: return QualType();
2987 case TargetInfo::SignedShort: return ShortTy;
2988 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2989 case TargetInfo::SignedInt: return IntTy;
2990 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2991 case TargetInfo::SignedLong: return LongTy;
2992 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2993 case TargetInfo::SignedLongLong: return LongLongTy;
2994 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2995 }
2996
2997 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbar7b0dcc22008-11-11 01:16:00 +00002998 return QualType();
Douglas Gregorc6507e42008-11-03 14:12:49 +00002999}
Ted Kremenek118930e2008-07-24 23:58:27 +00003000
3001//===----------------------------------------------------------------------===//
3002// Type Predicates.
3003//===----------------------------------------------------------------------===//
3004
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003005/// isObjCNSObjectType - Return true if this is an NSObject object using
3006/// NSObject attribute on a c-style pointer type.
3007/// FIXME - Make it work directly on types.
Steve Naroffad75bd22009-07-16 15:41:00 +00003008/// FIXME: Move to Type.
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003009///
3010bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3011 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3012 if (TypedefDecl *TD = TDT->getDecl())
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003013 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003014 return true;
3015 }
3016 return false;
3017}
3018
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00003019/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3020/// garbage collection attribute.
3021///
3022QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00003023 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00003024 if (getLangOptions().ObjC1 &&
3025 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00003026 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00003027 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00003028 // (or pointers to them) be treated as though they were declared
3029 // as __strong.
3030 if (GCAttrs == QualType::GCNone) {
Steve Naroffad75bd22009-07-16 15:41:00 +00003031 if (Ty->isObjCObjectPointerType())
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00003032 GCAttrs = QualType::Strong;
3033 else if (Ty->isPointerType())
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003034 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00003035 }
Fariborz Jahaniand7b01972009-04-11 00:00:54 +00003036 // Non-pointers have none gc'able attribute regardless of the attribute
3037 // set on them.
Steve Naroffad75bd22009-07-16 15:41:00 +00003038 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahaniand7b01972009-04-11 00:00:54 +00003039 return QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00003040 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00003041 return GCAttrs;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00003042}
3043
Chris Lattner6ff358b2008-04-07 06:51:04 +00003044//===----------------------------------------------------------------------===//
3045// Type Compatibility Testing
3046//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00003047
Chris Lattner6ff358b2008-04-07 06:51:04 +00003048/// areCompatVectorTypes - Return true if the two specified vector types are
3049/// compatible.
3050static bool areCompatVectorTypes(const VectorType *LHS,
3051 const VectorType *RHS) {
3052 assert(LHS->isCanonical() && RHS->isCanonical());
3053 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003054 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ff358b2008-04-07 06:51:04 +00003055}
3056
Steve Naroff99eb86b2009-07-23 01:01:38 +00003057//===----------------------------------------------------------------------===//
3058// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3059//===----------------------------------------------------------------------===//
3060
3061/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3062/// inheritance hierarchy of 'rProto'.
3063static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3064 ObjCProtocolDecl *rProto) {
3065 if (lProto == rProto)
3066 return true;
3067 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3068 E = rProto->protocol_end(); PI != E; ++PI)
3069 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3070 return true;
3071 return false;
3072}
3073
3074/// ClassImplementsProtocol - Checks that 'lProto' protocol
3075/// has been implemented in IDecl class, its super class or categories (if
3076/// lookupCategory is true).
3077static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
3078 ObjCInterfaceDecl *IDecl,
3079 bool lookupCategory,
3080 bool RHSIsQualifiedID = false) {
3081
3082 // 1st, look up the class.
3083 const ObjCList<ObjCProtocolDecl> &Protocols =
3084 IDecl->getReferencedProtocols();
3085
3086 for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
3087 E = Protocols.end(); PI != E; ++PI) {
3088 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3089 return true;
3090 // This is dubious and is added to be compatible with gcc. In gcc, it is
3091 // also allowed assigning a protocol-qualified 'id' type to a LHS object
3092 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
3093 // object. This IMO, should be a bug.
3094 // FIXME: Treat this as an extension, and flag this as an error when GCC
3095 // extensions are not enabled.
3096 if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto))
3097 return true;
3098 }
3099
3100 // 2nd, look up the category.
3101 if (lookupCategory)
3102 for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
3103 CDecl = CDecl->getNextClassCategory()) {
3104 for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
3105 E = CDecl->protocol_end(); PI != E; ++PI)
3106 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3107 return true;
3108 }
3109
3110 // 3rd, look up the super class(s)
3111 if (IDecl->getSuperClass())
3112 return
3113 ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory,
3114 RHSIsQualifiedID);
3115
3116 return false;
3117}
3118
3119/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3120/// return true if lhs's protocols conform to rhs's protocol; false
3121/// otherwise.
3122bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3123 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3124 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3125 return false;
3126}
3127
3128/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3129/// ObjCQualifiedIDType.
3130bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3131 bool compare) {
3132 // Allow id<P..> and an 'id' or void* type in all cases.
3133 if (lhs->isVoidPointerType() ||
3134 lhs->isObjCIdType() || lhs->isObjCClassType())
3135 return true;
3136 else if (rhs->isVoidPointerType() ||
3137 rhs->isObjCIdType() || rhs->isObjCClassType())
3138 return true;
3139
3140 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3141 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3142
3143 if (!rhsOPT) return false;
3144
3145 if (rhsOPT->qual_empty()) {
3146 // If the RHS is a unqualified interface pointer "NSString*",
3147 // make sure we check the class hierarchy.
3148 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3149 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3150 E = lhsQID->qual_end(); I != E; ++I) {
3151 // when comparing an id<P> on lhs with a static type on rhs,
3152 // see if static class implements all of id's protocols, directly or
3153 // through its super class and categories.
3154 if (!ClassImplementsProtocol(*I, rhsID, true))
3155 return false;
3156 }
3157 }
3158 // If there are no qualifiers and no interface, we have an 'id'.
3159 return true;
3160 }
3161 // Both the right and left sides have qualifiers.
3162 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3163 E = lhsQID->qual_end(); I != E; ++I) {
3164 ObjCProtocolDecl *lhsProto = *I;
3165 bool match = false;
3166
3167 // when comparing an id<P> on lhs with a static type on rhs,
3168 // see if static class implements all of id's protocols, directly or
3169 // through its super class and categories.
3170 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3171 E = rhsOPT->qual_end(); J != E; ++J) {
3172 ObjCProtocolDecl *rhsProto = *J;
3173 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3174 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3175 match = true;
3176 break;
3177 }
3178 }
3179 // If the RHS is a qualified interface pointer "NSString<P>*",
3180 // make sure we check the class hierarchy.
3181 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3182 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3183 E = lhsQID->qual_end(); I != E; ++I) {
3184 // when comparing an id<P> on lhs with a static type on rhs,
3185 // see if static class implements all of id's protocols, directly or
3186 // through its super class and categories.
3187 if (ClassImplementsProtocol(*I, rhsID, true)) {
3188 match = true;
3189 break;
3190 }
3191 }
3192 }
3193 if (!match)
3194 return false;
3195 }
3196
3197 return true;
3198 }
3199
3200 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3201 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3202
3203 if (const ObjCObjectPointerType *lhsOPT =
3204 lhs->getAsObjCInterfacePointerType()) {
3205 if (lhsOPT->qual_empty()) {
3206 bool match = false;
3207 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3208 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3209 E = rhsQID->qual_end(); I != E; ++I) {
3210 // when comparing an id<P> on lhs with a static type on rhs,
3211 // see if static class implements all of id's protocols, directly or
3212 // through its super class and categories.
3213 if (ClassImplementsProtocol(*I, lhsID, true)) {
3214 match = true;
3215 break;
3216 }
3217 }
3218 if (!match)
3219 return false;
3220 }
3221 return true;
3222 }
3223 // Both the right and left sides have qualifiers.
3224 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3225 E = lhsOPT->qual_end(); I != E; ++I) {
3226 ObjCProtocolDecl *lhsProto = *I;
3227 bool match = false;
3228
3229 // when comparing an id<P> on lhs with a static type on rhs,
3230 // see if static class implements all of id's protocols, directly or
3231 // through its super class and categories.
3232 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3233 E = rhsQID->qual_end(); J != E; ++J) {
3234 ObjCProtocolDecl *rhsProto = *J;
3235 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3236 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3237 match = true;
3238 break;
3239 }
3240 }
3241 if (!match)
3242 return false;
3243 }
3244 return true;
3245 }
3246 return false;
3247}
3248
Eli Friedman0d9549b2008-08-22 00:56:42 +00003249/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ff358b2008-04-07 06:51:04 +00003250/// compatible for assignment from RHS to LHS. This handles validation of any
3251/// protocol qualifiers on the LHS or RHS.
3252///
Steve Naroff329ec222009-07-10 23:34:53 +00003253bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3254 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003255 // If either type represents the built-in 'id' or 'Class' types, return true.
3256 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00003257 return true;
3258
Steve Naroff99eb86b2009-07-23 01:01:38 +00003259 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3260 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3261 QualType(RHSOPT,0),
3262 false);
3263
Steve Naroff329ec222009-07-10 23:34:53 +00003264 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3265 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff99eb86b2009-07-23 01:01:38 +00003266 if (LHS && RHS) // We have 2 user-defined types.
3267 return canAssignObjCInterfaces(LHS, RHS);
3268
3269 return false;
Steve Naroff329ec222009-07-10 23:34:53 +00003270}
3271
Eli Friedman0d9549b2008-08-22 00:56:42 +00003272bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3273 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00003274 // Verify that the base decls are compatible: the RHS must be a subclass of
3275 // the LHS.
3276 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3277 return false;
3278
3279 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3280 // protocol qualified at all, then we are good.
Steve Naroff77763c52009-07-18 15:33:26 +00003281 if (LHS->getNumProtocols() == 0)
Chris Lattner6ff358b2008-04-07 06:51:04 +00003282 return true;
3283
3284 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3285 // isn't a superset.
Steve Naroff77763c52009-07-18 15:33:26 +00003286 if (RHS->getNumProtocols() == 0)
Chris Lattner6ff358b2008-04-07 06:51:04 +00003287 return true; // FIXME: should return false!
3288
Steve Naroff77763c52009-07-18 15:33:26 +00003289 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3290 LHSPE = LHS->qual_end();
Steve Naroff98e71b82009-03-01 16:12:44 +00003291 LHSPI != LHSPE; LHSPI++) {
3292 bool RHSImplementsProtocol = false;
3293
3294 // If the RHS doesn't implement the protocol on the left, the types
3295 // are incompatible.
Steve Naroff77763c52009-07-18 15:33:26 +00003296 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff99eb86b2009-07-23 01:01:38 +00003297 RHSPE = RHS->qual_end();
Steve Naroffa9604792009-07-16 16:21:02 +00003298 RHSPI != RHSPE; RHSPI++) {
3299 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff98e71b82009-03-01 16:12:44 +00003300 RHSImplementsProtocol = true;
Steve Naroffa9604792009-07-16 16:21:02 +00003301 break;
3302 }
Steve Naroff98e71b82009-03-01 16:12:44 +00003303 }
3304 // FIXME: For better diagnostics, consider passing back the protocol name.
3305 if (!RHSImplementsProtocol)
3306 return false;
Chris Lattner6ff358b2008-04-07 06:51:04 +00003307 }
Steve Naroff98e71b82009-03-01 16:12:44 +00003308 // The RHS implements all protocols listed on the LHS.
3309 return true;
Chris Lattner6ff358b2008-04-07 06:51:04 +00003310}
3311
Steve Naroff17c03822009-02-12 17:52:19 +00003312bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3313 // get the "pointed to" types
Steve Naroff329ec222009-07-10 23:34:53 +00003314 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3315 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff17c03822009-02-12 17:52:19 +00003316
Steve Naroff329ec222009-07-10 23:34:53 +00003317 if (!LHSOPT || !RHSOPT)
Steve Naroff17c03822009-02-12 17:52:19 +00003318 return false;
Steve Naroff329ec222009-07-10 23:34:53 +00003319
3320 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3321 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff17c03822009-02-12 17:52:19 +00003322}
3323
Steve Naroff85f0dc52007-10-15 20:41:53 +00003324/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3325/// both shall have the identically qualified version of a compatible type.
3326/// C99 6.2.7p1: Two types have compatible types if their types are the
3327/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003328bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3329 return !mergeTypes(LHS, RHS).isNull();
3330}
3331
3332QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3333 const FunctionType *lbase = lhs->getAsFunctionType();
3334 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00003335 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3336 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003337 bool allLTypes = true;
3338 bool allRTypes = true;
3339
3340 // Check return type
3341 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3342 if (retType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003343 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3344 allLTypes = false;
3345 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3346 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003347
3348 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl2767d882009-05-27 22:11:52 +00003349 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3350 "C++ shouldn't be here");
Eli Friedman0d9549b2008-08-22 00:56:42 +00003351 unsigned lproto_nargs = lproto->getNumArgs();
3352 unsigned rproto_nargs = rproto->getNumArgs();
3353
3354 // Compatible functions must have the same number of arguments
3355 if (lproto_nargs != rproto_nargs)
3356 return QualType();
3357
3358 // Variadic and non-variadic functions aren't compatible
3359 if (lproto->isVariadic() != rproto->isVariadic())
3360 return QualType();
3361
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003362 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3363 return QualType();
3364
Eli Friedman0d9549b2008-08-22 00:56:42 +00003365 // Check argument compatibility
3366 llvm::SmallVector<QualType, 10> types;
3367 for (unsigned i = 0; i < lproto_nargs; i++) {
3368 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3369 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3370 QualType argtype = mergeTypes(largtype, rargtype);
3371 if (argtype.isNull()) return QualType();
3372 types.push_back(argtype);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003373 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3374 allLTypes = false;
3375 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3376 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003377 }
3378 if (allLTypes) return lhs;
3379 if (allRTypes) return rhs;
3380 return getFunctionType(retType, types.begin(), types.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003381 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00003382 }
3383
3384 if (lproto) allRTypes = false;
3385 if (rproto) allLTypes = false;
3386
Douglas Gregor4fa58902009-02-26 23:50:07 +00003387 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003388 if (proto) {
Sebastian Redl2767d882009-05-27 22:11:52 +00003389 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman0d9549b2008-08-22 00:56:42 +00003390 if (proto->isVariadic()) return QualType();
3391 // Check that the types are compatible with the types that
3392 // would result from default argument promotions (C99 6.7.5.3p15).
3393 // The only types actually affected are promotable integer
3394 // types and floats, which would be passed as a different
3395 // type depending on whether the prototype is visible.
3396 unsigned proto_nargs = proto->getNumArgs();
3397 for (unsigned i = 0; i < proto_nargs; ++i) {
3398 QualType argTy = proto->getArgType(i);
3399 if (argTy->isPromotableIntegerType() ||
3400 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3401 return QualType();
3402 }
3403
3404 if (allLTypes) return lhs;
3405 if (allRTypes) return rhs;
3406 return getFunctionType(retType, proto->arg_type_begin(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003407 proto->getNumArgs(), lproto->isVariadic(),
3408 lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00003409 }
3410
3411 if (allLTypes) return lhs;
3412 if (allRTypes) return rhs;
Douglas Gregor4fa58902009-02-26 23:50:07 +00003413 return getFunctionNoProtoType(retType);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003414}
3415
3416QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling6a9d8542007-12-03 07:33:35 +00003417 // C++ [expr]: If an expression initially has the type "reference to T", the
3418 // type is adjusted to "T" prior to any further analysis, the expression
3419 // designates the object or function denoted by the reference, and the
Sebastian Redlce6fff02009-03-16 23:22:08 +00003420 // expression is an lvalue unless the reference is an rvalue reference and
3421 // the expression is a function call (possibly inside parentheses).
Eli Friedman0d9549b2008-08-22 00:56:42 +00003422 // FIXME: C++ shouldn't be going through here! The rules are different
3423 // enough that they should be handled separately.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003424 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3425 // shouldn't be going through here!
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003426 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00003427 LHS = RT->getPointeeType();
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003428 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00003429 RHS = RT->getPointeeType();
Chris Lattnerd47d6042008-04-07 05:37:56 +00003430
Eli Friedman0d9549b2008-08-22 00:56:42 +00003431 QualType LHSCan = getCanonicalType(LHS),
3432 RHSCan = getCanonicalType(RHS);
3433
3434 // If two types are identical, they are compatible.
3435 if (LHSCan == RHSCan)
3436 return LHS;
3437
3438 // If the qualifiers are different, the types aren't compatible
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003439 // Note that we handle extended qualifiers later, in the
3440 // case for ExtQualType.
3441 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman0d9549b2008-08-22 00:56:42 +00003442 return QualType();
3443
Eli Friedmanaeae1ce2009-06-01 01:22:52 +00003444 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3445 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman0d9549b2008-08-22 00:56:42 +00003446
Chris Lattnerc38d4522008-01-14 05:45:46 +00003447 // We want to consider the two function types to be the same for these
3448 // comparisons, just force one to the other.
3449 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3450 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00003451
Eli Friedmande43bf62009-06-02 05:28:56 +00003452 // Strip off objc_gc attributes off the top level so they can be merged.
3453 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003454 if (RHSClass == Type::ExtQual) {
Eli Friedmande43bf62009-06-02 05:28:56 +00003455 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3456 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003457 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003458 // __weak attribute must appear on both declarations.
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003459 // __strong attribue is redundant if other decl is an objective-c
3460 // object pointer (or decorated with __strong attribute); otherwise
3461 // issue error.
3462 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3463 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff329ec222009-07-10 23:34:53 +00003464 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003465 return QualType();
3466
Eli Friedmande43bf62009-06-02 05:28:56 +00003467 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3468 RHS.getCVRQualifiers());
3469 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003470 if (!Result.isNull()) {
3471 if (Result.getObjCGCAttr() == QualType::GCNone)
3472 Result = getObjCGCQualType(Result, GCAttr);
3473 else if (Result.getObjCGCAttr() != GCAttr)
3474 Result = QualType();
3475 }
Eli Friedmande43bf62009-06-02 05:28:56 +00003476 return Result;
3477 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003478 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003479 if (LHSClass == Type::ExtQual) {
Eli Friedmande43bf62009-06-02 05:28:56 +00003480 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3481 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003482 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3483 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003484 // __strong attribue is redundant if other decl is an objective-c
3485 // object pointer (or decorated with __strong attribute); otherwise
3486 // issue error.
3487 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3488 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff329ec222009-07-10 23:34:53 +00003489 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003490 return QualType();
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003491
Eli Friedmande43bf62009-06-02 05:28:56 +00003492 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3493 LHS.getCVRQualifiers());
3494 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003495 if (!Result.isNull()) {
3496 if (Result.getObjCGCAttr() == QualType::GCNone)
3497 Result = getObjCGCQualType(Result, GCAttr);
3498 else if (Result.getObjCGCAttr() != GCAttr)
3499 Result = QualType();
3500 }
Eli Friedman430d9f12009-06-02 07:45:37 +00003501 return Result;
Eli Friedmande43bf62009-06-02 05:28:56 +00003502 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003503 }
3504
Eli Friedman398837e2008-02-12 08:23:06 +00003505 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00003506 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3507 LHSClass = Type::ConstantArray;
3508 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3509 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003510
Nate Begemanaf6ed502008-04-18 23:10:10 +00003511 // Canonicalize ExtVector -> Vector.
3512 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3513 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00003514
3515 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00003516 if (LHSClass != RHSClass) {
Chris Lattnerc38d4522008-01-14 05:45:46 +00003517 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3518 // a signed integer type, or an unsigned integer type.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003519 if (const EnumType* ETy = LHS->getAsEnumType()) {
3520 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3521 return RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00003522 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00003523 if (const EnumType* ETy = RHS->getAsEnumType()) {
3524 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3525 return LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00003526 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003527
Eli Friedman0d9549b2008-08-22 00:56:42 +00003528 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003529 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00003530
Steve Naroffc88babe2008-01-09 22:43:08 +00003531 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00003532 switch (LHSClass) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003533#define TYPE(Class, Base)
3534#define ABSTRACT_TYPE(Class, Base)
3535#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3536#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3537#include "clang/AST/TypeNodes.def"
3538 assert(false && "Non-canonical and dependent types shouldn't get here");
3539 return QualType();
3540
Sebastian Redlce6fff02009-03-16 23:22:08 +00003541 case Type::LValueReference:
3542 case Type::RValueReference:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003543 case Type::MemberPointer:
3544 assert(false && "C++ should never be in mergeTypes");
3545 return QualType();
3546
3547 case Type::IncompleteArray:
3548 case Type::VariableArray:
3549 case Type::FunctionProto:
3550 case Type::ExtVector:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003551 assert(false && "Types are eliminated above");
3552 return QualType();
3553
Chris Lattnerc38d4522008-01-14 05:45:46 +00003554 case Type::Pointer:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003555 {
3556 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003557 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3558 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
Eli Friedman0d9549b2008-08-22 00:56:42 +00003559 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3560 if (ResultType.isNull()) return QualType();
Eli Friedmande43bf62009-06-02 05:28:56 +00003561 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003562 return LHS;
Eli Friedmande43bf62009-06-02 05:28:56 +00003563 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003564 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003565 return getPointerType(ResultType);
3566 }
Steve Naroff09e1b9e2008-12-10 17:49:55 +00003567 case Type::BlockPointer:
3568 {
3569 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003570 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3571 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
Steve Naroff09e1b9e2008-12-10 17:49:55 +00003572 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3573 if (ResultType.isNull()) return QualType();
3574 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3575 return LHS;
3576 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3577 return RHS;
3578 return getBlockPointerType(ResultType);
3579 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003580 case Type::ConstantArray:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003581 {
3582 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3583 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3584 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3585 return QualType();
3586
3587 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3588 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3589 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3590 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003591 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3592 return LHS;
3593 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3594 return RHS;
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003595 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3596 ArrayType::ArraySizeModifier(), 0);
3597 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3598 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003599 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3600 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003601 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3602 return LHS;
3603 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3604 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003605 if (LVAT) {
3606 // FIXME: This isn't correct! But tricky to implement because
3607 // the array's size has to be the size of LHS, but the type
3608 // has to be different.
3609 return LHS;
3610 }
3611 if (RVAT) {
3612 // FIXME: This isn't correct! But tricky to implement because
3613 // the array's size has to be the size of RHS, but the type
3614 // has to be different.
3615 return RHS;
3616 }
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003617 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3618 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor1d381132009-07-06 15:59:29 +00003619 return getIncompleteArrayType(ResultType,
3620 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003621 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003622 case Type::FunctionNoProto:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003623 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor4fa58902009-02-26 23:50:07 +00003624 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003625 case Type::Enum:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003626 return QualType();
Chris Lattnerc38d4522008-01-14 05:45:46 +00003627 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003628 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003629 return QualType();
Daniel Dunbar457f33d2009-01-28 21:22:12 +00003630 case Type::Complex:
3631 // Distinct complex types are incompatible.
3632 return QualType();
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003633 case Type::Vector:
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003634 // FIXME: The merged type should be an ExtVector!
Eli Friedman0d9549b2008-08-22 00:56:42 +00003635 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3636 return LHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003637 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003638 case Type::ObjCInterface: {
Steve Naroff0bbc1352009-02-21 16:18:07 +00003639 // Check if the interfaces are assignment compatible.
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003640 // FIXME: This should be type compatibility, e.g. whether
3641 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff0bbc1352009-02-21 16:18:07 +00003642 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3643 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3644 if (LHSIface && RHSIface &&
3645 canAssignObjCInterfaces(LHSIface, RHSIface))
3646 return LHS;
3647
Eli Friedman0d9549b2008-08-22 00:56:42 +00003648 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003649 }
Steve Naroff329ec222009-07-10 23:34:53 +00003650 case Type::ObjCObjectPointer: {
Steve Naroff329ec222009-07-10 23:34:53 +00003651 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3652 RHS->getAsObjCObjectPointerType()))
3653 return LHS;
3654
Steve Naroff28ceff72008-12-10 22:14:21 +00003655 return QualType();
Steve Naroff329ec222009-07-10 23:34:53 +00003656 }
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003657 case Type::FixedWidthInt:
3658 // Distinct fixed-width integers are not compatible.
3659 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003660 case Type::ExtQual:
3661 // FIXME: ExtQual types can be compatible even if they're not
3662 // identical!
3663 return QualType();
3664 // First attempt at an implementation, but I'm not really sure it's
3665 // right...
3666#if 0
3667 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3668 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3669 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3670 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3671 return QualType();
3672 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3673 LHSBase = QualType(LQual->getBaseType(), 0);
3674 RHSBase = QualType(RQual->getBaseType(), 0);
3675 ResultType = mergeTypes(LHSBase, RHSBase);
3676 if (ResultType.isNull()) return QualType();
3677 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3678 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3679 return LHS;
3680 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3681 return RHS;
3682 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3683 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3684 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3685 return ResultType;
3686#endif
Douglas Gregordd13e842009-03-30 22:58:21 +00003687
3688 case Type::TemplateSpecialization:
3689 assert(false && "Dependent types have no size");
3690 break;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003691 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00003692
3693 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003694}
Ted Kremenek738e6c02007-10-31 17:10:13 +00003695
Chris Lattner1d78a862008-04-07 07:01:58 +00003696//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00003697// Integer Predicates
3698//===----------------------------------------------------------------------===//
Chris Lattner74f67012009-01-16 07:15:35 +00003699
Eli Friedman0832dbc2008-06-28 06:23:08 +00003700unsigned ASTContext::getIntWidth(QualType T) {
3701 if (T == BoolTy)
3702 return 1;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00003703 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3704 return FWIT->getWidth();
3705 }
3706 // For builtin types, just use the standard type sizing method
Eli Friedman0832dbc2008-06-28 06:23:08 +00003707 return (unsigned)getTypeSize(T);
3708}
3709
3710QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3711 assert(T->isSignedIntegerType() && "Unexpected type");
3712 if (const EnumType* ETy = T->getAsEnumType())
3713 T = ETy->getDecl()->getIntegerType();
3714 const BuiltinType* BTy = T->getAsBuiltinType();
3715 assert (BTy && "Unexpected signed integer type");
3716 switch (BTy->getKind()) {
3717 case BuiltinType::Char_S:
3718 case BuiltinType::SChar:
3719 return UnsignedCharTy;
3720 case BuiltinType::Short:
3721 return UnsignedShortTy;
3722 case BuiltinType::Int:
3723 return UnsignedIntTy;
3724 case BuiltinType::Long:
3725 return UnsignedLongTy;
3726 case BuiltinType::LongLong:
3727 return UnsignedLongLongTy;
Chris Lattner6cc7e412009-04-30 02:43:43 +00003728 case BuiltinType::Int128:
3729 return UnsignedInt128Ty;
Eli Friedman0832dbc2008-06-28 06:23:08 +00003730 default:
3731 assert(0 && "Unexpected signed integer type");
3732 return QualType();
3733 }
3734}
3735
Douglas Gregorc34897d2009-04-09 22:27:44 +00003736ExternalASTSource::~ExternalASTSource() { }
3737
3738void ExternalASTSource::PrintStats() { }
Chris Lattner260ad502009-06-14 00:45:47 +00003739
3740
3741//===----------------------------------------------------------------------===//
3742// Builtin Type Computation
3743//===----------------------------------------------------------------------===//
3744
3745/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3746/// pointer over the consumed characters. This returns the resultant type.
3747static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3748 ASTContext::GetBuiltinTypeError &Error,
3749 bool AllowTypeModifiers = true) {
3750 // Modifiers.
3751 int HowLong = 0;
3752 bool Signed = false, Unsigned = false;
3753
3754 // Read the modifiers first.
3755 bool Done = false;
3756 while (!Done) {
3757 switch (*Str++) {
3758 default: Done = true; --Str; break;
3759 case 'S':
3760 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3761 assert(!Signed && "Can't use 'S' modifier multiple times!");
3762 Signed = true;
3763 break;
3764 case 'U':
3765 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3766 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3767 Unsigned = true;
3768 break;
3769 case 'L':
3770 assert(HowLong <= 2 && "Can't have LLLL modifier");
3771 ++HowLong;
3772 break;
3773 }
3774 }
3775
3776 QualType Type;
3777
3778 // Read the base type.
3779 switch (*Str++) {
3780 default: assert(0 && "Unknown builtin type letter!");
3781 case 'v':
3782 assert(HowLong == 0 && !Signed && !Unsigned &&
3783 "Bad modifiers used with 'v'!");
3784 Type = Context.VoidTy;
3785 break;
3786 case 'f':
3787 assert(HowLong == 0 && !Signed && !Unsigned &&
3788 "Bad modifiers used with 'f'!");
3789 Type = Context.FloatTy;
3790 break;
3791 case 'd':
3792 assert(HowLong < 2 && !Signed && !Unsigned &&
3793 "Bad modifiers used with 'd'!");
3794 if (HowLong)
3795 Type = Context.LongDoubleTy;
3796 else
3797 Type = Context.DoubleTy;
3798 break;
3799 case 's':
3800 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3801 if (Unsigned)
3802 Type = Context.UnsignedShortTy;
3803 else
3804 Type = Context.ShortTy;
3805 break;
3806 case 'i':
3807 if (HowLong == 3)
3808 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3809 else if (HowLong == 2)
3810 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3811 else if (HowLong == 1)
3812 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3813 else
3814 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3815 break;
3816 case 'c':
3817 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3818 if (Signed)
3819 Type = Context.SignedCharTy;
3820 else if (Unsigned)
3821 Type = Context.UnsignedCharTy;
3822 else
3823 Type = Context.CharTy;
3824 break;
3825 case 'b': // boolean
3826 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3827 Type = Context.BoolTy;
3828 break;
3829 case 'z': // size_t.
3830 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3831 Type = Context.getSizeType();
3832 break;
3833 case 'F':
3834 Type = Context.getCFConstantStringType();
3835 break;
3836 case 'a':
3837 Type = Context.getBuiltinVaListType();
3838 assert(!Type.isNull() && "builtin va list type not initialized!");
3839 break;
3840 case 'A':
3841 // This is a "reference" to a va_list; however, what exactly
3842 // this means depends on how va_list is defined. There are two
3843 // different kinds of va_list: ones passed by value, and ones
3844 // passed by reference. An example of a by-value va_list is
3845 // x86, where va_list is a char*. An example of by-ref va_list
3846 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3847 // we want this argument to be a char*&; for x86-64, we want
3848 // it to be a __va_list_tag*.
3849 Type = Context.getBuiltinVaListType();
3850 assert(!Type.isNull() && "builtin va list type not initialized!");
3851 if (Type->isArrayType()) {
3852 Type = Context.getArrayDecayedType(Type);
3853 } else {
3854 Type = Context.getLValueReferenceType(Type);
3855 }
3856 break;
3857 case 'V': {
3858 char *End;
3859
3860 unsigned NumElements = strtoul(Str, &End, 10);
3861 assert(End != Str && "Missing vector size");
3862
3863 Str = End;
3864
3865 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3866 Type = Context.getVectorType(ElementType, NumElements);
3867 break;
3868 }
3869 case 'P': {
Douglas Gregor151fac72009-07-07 16:35:42 +00003870 Type = Context.getFILEType();
3871 if (Type.isNull()) {
Chris Lattner260ad502009-06-14 00:45:47 +00003872 Error = ASTContext::GE_Missing_FILE;
3873 return QualType();
Douglas Gregor151fac72009-07-07 16:35:42 +00003874 } else {
3875 break;
Chris Lattner260ad502009-06-14 00:45:47 +00003876 }
3877 }
3878 }
3879
3880 if (!AllowTypeModifiers)
3881 return Type;
3882
3883 Done = false;
3884 while (!Done) {
3885 switch (*Str++) {
3886 default: Done = true; --Str; break;
3887 case '*':
3888 Type = Context.getPointerType(Type);
3889 break;
3890 case '&':
3891 Type = Context.getLValueReferenceType(Type);
3892 break;
3893 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3894 case 'C':
3895 Type = Type.getQualifiedType(QualType::Const);
3896 break;
3897 }
3898 }
3899
3900 return Type;
3901}
3902
3903/// GetBuiltinType - Return the type for the specified builtin.
3904QualType ASTContext::GetBuiltinType(unsigned id,
3905 GetBuiltinTypeError &Error) {
3906 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3907
3908 llvm::SmallVector<QualType, 8> ArgTypes;
3909
3910 Error = GE_None;
3911 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3912 if (Error != GE_None)
3913 return QualType();
3914 while (TypeStr[0] && TypeStr[0] != '.') {
3915 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3916 if (Error != GE_None)
3917 return QualType();
3918
3919 // Do array -> pointer decay. The builtin should use the decayed type.
3920 if (Ty->isArrayType())
3921 Ty = getArrayDecayedType(Ty);
3922
3923 ArgTypes.push_back(Ty);
3924 }
3925
3926 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3927 "'.' should only occur at end of builtin type list!");
3928
3929 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3930 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3931 return getFunctionNoProtoType(ResType);
3932 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3933 TypeStr[0] == '.', 0);
3934}