blob: 08607d5ed24f276f2bac130c04100777819a5e55 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner61710852008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000036 Builtin::Context &builtins,
37 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000038 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
39 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000040 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
41 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000042 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000043 if (size_reserve > 0) Types.reserve(size_reserve);
44 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000045 TUDecl = TranslationUnitDecl::Create(*this);
46}
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048ASTContext::~ASTContext() {
49 // Deallocate all the types.
50 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000051 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000052 Types.pop_back();
53 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000054
Nuno Lopesb74668e2008-12-17 22:30:25 +000055 {
56 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
57 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
58 while (I != E) {
59 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
60 delete R;
61 }
62 }
63
64 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000065 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
66 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000067 while (I != E) {
68 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
69 delete R;
70 }
71 }
72
Douglas Gregorab452ba2009-03-26 23:50:42 +000073 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000074 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
75 NNS = NestedNameSpecifiers.begin(),
76 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000077 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000078 /* Increment in loop */)
79 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000080
81 if (GlobalNestedNameSpecifier)
82 GlobalNestedNameSpecifier->Destroy(*this);
83
Eli Friedmanb26153c2008-05-27 03:08:09 +000084 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
86
Douglas Gregor2cf26342009-04-09 22:27:44 +000087void
88ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
89 ExternalSource.reset(Source.take());
90}
91
Reid Spencer5f016e22007-07-11 17:01:13 +000092void ASTContext::PrintStats() const {
93 fprintf(stderr, "*** AST Context Stats:\n");
94 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000095
Douglas Gregordbe833d2009-05-26 14:40:08 +000096 unsigned counts[] = {
97#define TYPE(Name, Parent) 0,
98#define ABSTRACT_TYPE(Name, Parent)
99#include "clang/AST/TypeNodes.def"
100 0 // Extra
101 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
104 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000105 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 }
107
Douglas Gregordbe833d2009-05-26 14:40:08 +0000108 unsigned Idx = 0;
109 unsigned TotalBytes = 0;
110#define TYPE(Name, Parent) \
111 if (counts[Idx]) \
112 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
113 TotalBytes += counts[Idx] * sizeof(Name##Type); \
114 ++Idx;
115#define ABSTRACT_TYPE(Name, Parent)
116#include "clang/AST/TypeNodes.def"
117
118 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000119
120 if (ExternalSource.get()) {
121 fprintf(stderr, "\n");
122 ExternalSource->PrintStats();
123 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000124}
125
126
127void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000128 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
Reid Spencer5f016e22007-07-11 17:01:13 +0000131void ASTContext::InitBuiltinTypes() {
132 assert(VoidTy.isNull() && "Context reinitialized?");
133
134 // C99 6.2.5p19.
135 InitBuiltinType(VoidTy, BuiltinType::Void);
136
137 // C99 6.2.5p2.
138 InitBuiltinType(BoolTy, BuiltinType::Bool);
139 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000140 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 InitBuiltinType(CharTy, BuiltinType::Char_S);
142 else
143 InitBuiltinType(CharTy, BuiltinType::Char_U);
144 // C99 6.2.5p4.
145 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
146 InitBuiltinType(ShortTy, BuiltinType::Short);
147 InitBuiltinType(IntTy, BuiltinType::Int);
148 InitBuiltinType(LongTy, BuiltinType::Long);
149 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
150
151 // C99 6.2.5p6.
152 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
153 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
154 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
155 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
156 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
157
158 // C99 6.2.5p10.
159 InitBuiltinType(FloatTy, BuiltinType::Float);
160 InitBuiltinType(DoubleTy, BuiltinType::Double);
161 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000162
Chris Lattner2df9ced2009-04-30 02:43:43 +0000163 // GNU extension, 128-bit integers.
164 InitBuiltinType(Int128Ty, BuiltinType::Int128);
165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
166
Chris Lattner3a250322009-02-26 23:43:47 +0000167 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
168 InitBuiltinType(WCharTy, BuiltinType::WChar);
169 else // C99
170 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000171
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000173 InitBuiltinType(OverloadTy, BuiltinType::Overload);
174
175 // Placeholder type for type-dependent expressions whose type is
176 // completely unknown. No code should ever check a type against
177 // DependentTy and users should never see it; however, it is here to
178 // help diagnose failures to properly check for type-dependent
179 // expressions.
180 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000181
Anders Carlssone89d1592009-06-26 18:41:36 +0000182 // Placeholder type for C++0x auto declarations whose real type has
183 // not yet been deduced.
184 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // C99 6.2.5p11.
187 FloatComplexTy = getComplexType(FloatTy);
188 DoubleComplexTy = getComplexType(DoubleTy);
189 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190
Steve Naroff7e219e42007-10-15 14:41:52 +0000191 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000193 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000194 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000195 ClassStructType = 0;
196
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000198
199 // void * type
200 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000201
202 // nullptr type (C++0x 2.14.7)
203 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
Douglas Gregor2e222532009-07-02 17:08:52 +0000206namespace {
207 class BeforeInTranslationUnit
208 : std::binary_function<SourceRange, SourceRange, bool> {
209 SourceManager *SourceMgr;
210
211 public:
212 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
213
214 bool operator()(SourceRange X, SourceRange Y) {
215 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
216 }
217 };
218}
219
220/// \brief Determine whether the given comment is a Doxygen-style comment.
221///
222/// \param Start the start of the comment text.
223///
224/// \param End the end of the comment text.
225///
226/// \param Member whether we want to check whether this is a member comment
227/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
228/// we only return true when we find a non-member comment.
229static bool
230isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
231 bool Member = false) {
232 const char *BufferStart
233 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
234 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
235 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
236
237 if (End - Start < 4)
238 return false;
239
240 assert(Start[0] == '/' && "Not a comment?");
241 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
242 return false;
243 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
244 return false;
245
246 return (Start[3] == '<') == Member;
247}
248
249/// \brief Retrieve the comment associated with the given declaration, if
250/// it has one.
251const char *ASTContext::getCommentForDecl(const Decl *D) {
252 if (!D)
253 return 0;
254
255 // Check whether we have cached a comment string for this declaration
256 // already.
257 llvm::DenseMap<const Decl *, std::string>::iterator Pos
258 = DeclComments.find(D);
259 if (Pos != DeclComments.end())
260 return Pos->second.c_str();
261
262 // If we have an external AST source and have not yet loaded comments from
263 // that source, do so now.
264 if (ExternalSource && !LoadedExternalComments) {
265 std::vector<SourceRange> LoadedComments;
266 ExternalSource->ReadComments(LoadedComments);
267
268 if (!LoadedComments.empty())
269 Comments.insert(Comments.begin(), LoadedComments.begin(),
270 LoadedComments.end());
271
272 LoadedExternalComments = true;
273 }
274
275 // If there are no comments anywhere, we won't find anything.
276 if (Comments.empty())
277 return 0;
278
279 // If the declaration doesn't map directly to a location in a file, we
280 // can't find the comment.
281 SourceLocation DeclStartLoc = D->getLocStart();
282 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
283 return 0;
284
285 // Find the comment that occurs just before this declaration.
286 std::vector<SourceRange>::iterator LastComment
287 = std::lower_bound(Comments.begin(), Comments.end(),
288 SourceRange(DeclStartLoc),
289 BeforeInTranslationUnit(&SourceMgr));
290
291 // Decompose the location for the start of the declaration and find the
292 // beginning of the file buffer.
293 std::pair<FileID, unsigned> DeclStartDecomp
294 = SourceMgr.getDecomposedLoc(DeclStartLoc);
295 const char *FileBufferStart
296 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
297
298 // First check whether we have a comment for a member.
299 if (LastComment != Comments.end() &&
300 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
301 isDoxygenComment(SourceMgr, *LastComment, true)) {
302 std::pair<FileID, unsigned> LastCommentEndDecomp
303 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
304 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
305 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
306 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
307 LastCommentEndDecomp.second)) {
308 // The Doxygen member comment comes after the declaration starts and
309 // is on the same line and in the same file as the declaration. This
310 // is the comment we want.
311 std::string &Result = DeclComments[D];
312 Result.append(FileBufferStart +
313 SourceMgr.getFileOffset(LastComment->getBegin()),
314 FileBufferStart + LastCommentEndDecomp.second + 1);
315 return Result.c_str();
316 }
317 }
318
319 if (LastComment == Comments.begin())
320 return 0;
321 --LastComment;
322
323 // Decompose the end of the comment.
324 std::pair<FileID, unsigned> LastCommentEndDecomp
325 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
326
327 // If the comment and the declaration aren't in the same file, then they
328 // aren't related.
329 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
330 return 0;
331
332 // Check that we actually have a Doxygen comment.
333 if (!isDoxygenComment(SourceMgr, *LastComment))
334 return 0;
335
336 // Compute the starting line for the declaration and for the end of the
337 // comment (this is expensive).
338 unsigned DeclStartLine
339 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
340 unsigned CommentEndLine
341 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
342 LastCommentEndDecomp.second);
343
344 // If the comment does not end on the line prior to the declaration, then
345 // the comment is not associated with the declaration at all.
346 if (CommentEndLine + 1 != DeclStartLine)
347 return 0;
348
349 // We have a comment, but there may be more comments on the previous lines.
350 // Keep looking so long as the comments are still Doxygen comments and are
351 // still adjacent.
352 unsigned ExpectedLine
353 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
354 std::vector<SourceRange>::iterator FirstComment = LastComment;
355 while (FirstComment != Comments.begin()) {
356 // Look at the previous comment
357 --FirstComment;
358 std::pair<FileID, unsigned> Decomp
359 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
360
361 // If this previous comment is in a different file, we're done.
362 if (Decomp.first != DeclStartDecomp.first) {
363 ++FirstComment;
364 break;
365 }
366
367 // If this comment is not a Doxygen comment, we're done.
368 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
369 ++FirstComment;
370 break;
371 }
372
373 // If the line number is not what we expected, we're done.
374 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
375 if (Line != ExpectedLine) {
376 ++FirstComment;
377 break;
378 }
379
380 // Set the next expected line number.
381 ExpectedLine
382 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
383 }
384
385 // The iterator range [FirstComment, LastComment] contains all of the
386 // BCPL comments that, together, are associated with this declaration.
387 // Form a single comment block string for this declaration that concatenates
388 // all of these comments.
389 std::string &Result = DeclComments[D];
390 while (FirstComment != LastComment) {
391 std::pair<FileID, unsigned> DecompStart
392 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
393 std::pair<FileID, unsigned> DecompEnd
394 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
395 Result.append(FileBufferStart + DecompStart.second,
396 FileBufferStart + DecompEnd.second + 1);
397 ++FirstComment;
398 }
399
400 // Append the last comment line.
401 Result.append(FileBufferStart +
402 SourceMgr.getFileOffset(LastComment->getBegin()),
403 FileBufferStart + LastCommentEndDecomp.second + 1);
404 return Result.c_str();
405}
406
Chris Lattner464175b2007-07-18 17:52:12 +0000407//===----------------------------------------------------------------------===//
408// Type Sizing and Analysis
409//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000410
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000411/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
412/// scalar floating point type.
413const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
414 const BuiltinType *BT = T->getAsBuiltinType();
415 assert(BT && "Not a floating point type!");
416 switch (BT->getKind()) {
417 default: assert(0 && "Not a floating point type!");
418 case BuiltinType::Float: return Target.getFloatFormat();
419 case BuiltinType::Double: return Target.getDoubleFormat();
420 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
421 }
422}
423
Chris Lattneraf707ab2009-01-24 21:53:27 +0000424/// getDeclAlign - Return a conservative estimate of the alignment of the
425/// specified decl. Note that bitfields do not have a valid alignment, so
426/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000427unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000428 unsigned Align = Target.getCharWidth();
429
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000430 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000431 Align = std::max(Align, AA->getAlignment());
432
Chris Lattneraf707ab2009-01-24 21:53:27 +0000433 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
434 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000435 if (const ReferenceType* RT = T->getAsReferenceType()) {
436 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000437 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000438 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
439 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000440 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
441 T = cast<ArrayType>(T)->getElementType();
442
443 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
444 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000445 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000446
447 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000448}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000449
Chris Lattnera7674d82007-07-13 22:13:22 +0000450/// getTypeSize - Return the size of the specified type, in bits. This method
451/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000452std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000453ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000454 uint64_t Width=0;
455 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000456 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000457#define TYPE(Class, Base)
458#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000459#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000460#define DEPENDENT_TYPE(Class, Base) case Type::Class:
461#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000462 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000463 break;
464
Chris Lattner692233e2007-07-13 22:27:08 +0000465 case Type::FunctionNoProto:
466 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000467 // GCC extension: alignof(function) = 32 bits
468 Width = 0;
469 Align = 32;
470 break;
471
Douglas Gregor72564e72009-02-26 23:50:07 +0000472 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000473 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000474 Width = 0;
475 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
476 break;
477
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000478 case Type::ConstantArrayWithExpr:
479 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000480 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000481 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000482
Chris Lattner98be4942008-03-05 18:54:05 +0000483 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000484 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000485 Align = EltInfo.second;
486 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000487 }
Nate Begeman213541a2008-04-18 23:10:10 +0000488 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000489 case Type::Vector: {
490 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000491 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000492 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000493 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000494 // If the alignment is not a power of 2, round up to the next power of 2.
495 // This happens for non-power-of-2 length vectors.
496 // FIXME: this should probably be a target property.
497 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000498 break;
499 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000500
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000501 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000502 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000503 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000504 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000505 // GCC extension: alignof(void) = 8 bits.
506 Width = 0;
507 Align = 8;
508 break;
509
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000510 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000511 Width = Target.getBoolWidth();
512 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000513 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000514 case BuiltinType::Char_S:
515 case BuiltinType::Char_U:
516 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000517 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000518 Width = Target.getCharWidth();
519 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000520 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000521 case BuiltinType::WChar:
522 Width = Target.getWCharWidth();
523 Align = Target.getWCharAlign();
524 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000525 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000526 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000527 Width = Target.getShortWidth();
528 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000529 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000530 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000531 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000532 Width = Target.getIntWidth();
533 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000534 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000535 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000536 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000537 Width = Target.getLongWidth();
538 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000539 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000540 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000541 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000542 Width = Target.getLongLongWidth();
543 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000544 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000545 case BuiltinType::Int128:
546 case BuiltinType::UInt128:
547 Width = 128;
548 Align = 128; // int128_t is 128-bit aligned on all targets.
549 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000550 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000551 Width = Target.getFloatWidth();
552 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000553 break;
554 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000555 Width = Target.getDoubleWidth();
556 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000557 break;
558 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000559 Width = Target.getLongDoubleWidth();
560 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000561 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000562 case BuiltinType::NullPtr:
563 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
564 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000565 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000566 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000567 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000568 case Type::FixedWidthInt:
569 // FIXME: This isn't precisely correct; the width/alignment should depend
570 // on the available types for the target
571 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000572 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000573 Align = Width;
574 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000575 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000576 // FIXME: Pointers into different addr spaces could have different sizes and
577 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000578 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000579 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000580 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000581 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000582 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000583 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000584 case Type::BlockPointer: {
585 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
586 Width = Target.getPointerWidth(AS);
587 Align = Target.getPointerAlign(AS);
588 break;
589 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000590 case Type::Pointer: {
591 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000592 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000593 Align = Target.getPointerAlign(AS);
594 break;
595 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000596 case Type::LValueReference:
597 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000598 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000599 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000600 // FIXME: This is wrong for struct layout: a reference in a struct has
601 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000602 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000603 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000604 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
605 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
606 // If we ever want to support other ABIs this needs to be abstracted.
607
Sebastian Redlf30208a2009-01-24 21:16:55 +0000608 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000609 std::pair<uint64_t, unsigned> PtrDiffInfo =
610 getTypeInfo(getPointerDiffType());
611 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000612 if (Pointee->isFunctionType())
613 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000614 Align = PtrDiffInfo.second;
615 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000616 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000617 case Type::Complex: {
618 // Complex types have the same alignment as their elements, but twice the
619 // size.
620 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000621 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000623 Align = EltInfo.second;
624 break;
625 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000626 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000627 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000628 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
629 Width = Layout.getSize();
630 Align = Layout.getAlignment();
631 break;
632 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000633 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000634 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000635 const TagType *TT = cast<TagType>(T);
636
637 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000638 Width = 1;
639 Align = 1;
640 break;
641 }
642
Daniel Dunbar1d751182008-11-08 05:48:37 +0000643 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000644 return getTypeInfo(ET->getDecl()->getIntegerType());
645
Daniel Dunbar1d751182008-11-08 05:48:37 +0000646 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000647 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
648 Width = Layout.getSize();
649 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000650 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000651 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000652
Douglas Gregor18857642009-04-30 17:32:17 +0000653 case Type::Typedef: {
654 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000655 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000656 Align = Aligned->getAlignment();
657 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
658 } else
659 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000660 break;
Chris Lattner71763312008-04-06 22:05:18 +0000661 }
Douglas Gregor18857642009-04-30 17:32:17 +0000662
663 case Type::TypeOfExpr:
664 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
665 .getTypePtr());
666
667 case Type::TypeOf:
668 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
669
Anders Carlsson395b4752009-06-24 19:06:50 +0000670 case Type::Decltype:
671 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
672 .getTypePtr());
673
Douglas Gregor18857642009-04-30 17:32:17 +0000674 case Type::QualifiedName:
675 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
676
677 case Type::TemplateSpecialization:
678 assert(getCanonicalType(T) != T &&
679 "Cannot request the size of a dependent type");
680 // FIXME: this is likely to be wrong once we support template
681 // aliases, since a template alias could refer to a typedef that
682 // has an __aligned__ attribute on it.
683 return getTypeInfo(getCanonicalType(T));
684 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000685
Chris Lattner464175b2007-07-18 17:52:12 +0000686 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000687 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000688}
689
Chris Lattner34ebde42009-01-27 18:08:34 +0000690/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
691/// type for the current target in bits. This can be different than the ABI
692/// alignment in cases where it is beneficial for performance to overalign
693/// a data type.
694unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
695 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000696
697 // Double and long long should be naturally aligned if possible.
698 if (const ComplexType* CT = T->getAsComplexType())
699 T = CT->getElementType().getTypePtr();
700 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
701 T->isSpecificBuiltinType(BuiltinType::LongLong))
702 return std::max(ABIAlign, (unsigned)getTypeSize(T));
703
Chris Lattner34ebde42009-01-27 18:08:34 +0000704 return ABIAlign;
705}
706
707
Devang Patel8b277042008-06-04 21:22:16 +0000708/// LayoutField - Field layout.
709void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000710 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000711 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000712 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000713 uint64_t FieldOffset = IsUnion ? 0 : Size;
714 uint64_t FieldSize;
715 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000716
717 // FIXME: Should this override struct packing? Probably we want to
718 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000719 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000720 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000721
722 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
723 // TODO: Need to check this algorithm on other targets!
724 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000725 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000726
727 std::pair<uint64_t, unsigned> FieldInfo =
728 Context.getTypeInfo(FD->getType());
729 uint64_t TypeSize = FieldInfo.first;
730
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000731 // Determine the alignment of this bitfield. The packing
732 // attributes define a maximum and the alignment attribute defines
733 // a minimum.
734 // FIXME: What is the right behavior when the specified alignment
735 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000736 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000737 if (FieldPacking)
738 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000739 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000740 FieldAlign = std::max(FieldAlign, AA->getAlignment());
741
742 // Check if we need to add padding to give the field the correct
743 // alignment.
744 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
745 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
746
747 // Padding members don't affect overall alignment
748 if (!FD->getIdentifier())
749 FieldAlign = 1;
750 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000751 if (FD->getType()->isIncompleteArrayType()) {
752 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000753 // query getTypeInfo about these, so we figure it out here.
754 // Flexible array members don't have any size, but they
755 // have to be aligned appropriately for their element type.
756 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000757 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000758 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000759 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
760 unsigned AS = RT->getPointeeType().getAddressSpace();
761 FieldSize = Context.Target.getPointerWidth(AS);
762 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000763 } else {
764 std::pair<uint64_t, unsigned> FieldInfo =
765 Context.getTypeInfo(FD->getType());
766 FieldSize = FieldInfo.first;
767 FieldAlign = FieldInfo.second;
768 }
769
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000770 // Determine the alignment of this bitfield. The packing
771 // attributes define a maximum and the alignment attribute defines
772 // a minimum. Additionally, the packing alignment must be at least
773 // a byte for non-bitfields.
774 //
775 // FIXME: What is the right behavior when the specified alignment
776 // is smaller than the specified packing?
777 if (FieldPacking)
778 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000779 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000780 FieldAlign = std::max(FieldAlign, AA->getAlignment());
781
782 // Round up the current record size to the field's alignment boundary.
783 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
784 }
785
786 // Place this field at the current location.
787 FieldOffsets[FieldNo] = FieldOffset;
788
789 // Reserve space for this field.
790 if (IsUnion) {
791 Size = std::max(Size, FieldSize);
792 } else {
793 Size = FieldOffset + FieldSize;
794 }
795
Daniel Dunbard6884a02009-05-04 05:16:21 +0000796 // Remember the next available offset.
797 NextOffset = Size;
798
Devang Patel8b277042008-06-04 21:22:16 +0000799 // Remember max struct/class alignment.
800 Alignment = std::max(Alignment, FieldAlign);
801}
802
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000803static void CollectLocalObjCIvars(ASTContext *Ctx,
804 const ObjCInterfaceDecl *OI,
805 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000806 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
807 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000808 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000809 if (!IVDecl->isInvalidDecl())
810 Fields.push_back(cast<FieldDecl>(IVDecl));
811 }
812}
813
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000814void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
815 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
816 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
817 CollectObjCIvars(SuperClass, Fields);
818 CollectLocalObjCIvars(this, OI, Fields);
819}
820
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000821/// ShallowCollectObjCIvars -
822/// Collect all ivars, including those synthesized, in the current class.
823///
824void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
825 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
826 bool CollectSynthesized) {
827 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
828 E = OI->ivar_end(); I != E; ++I) {
829 Ivars.push_back(*I);
830 }
831 if (CollectSynthesized)
832 CollectSynthesizedIvars(OI, Ivars);
833}
834
Fariborz Jahanian98200742009-05-12 18:14:29 +0000835void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
836 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000837 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
838 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000839 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
840 Ivars.push_back(Ivar);
841
842 // Also look into nested protocols.
843 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
844 E = PD->protocol_end(); P != E; ++P)
845 CollectProtocolSynthesizedIvars(*P, Ivars);
846}
847
848/// CollectSynthesizedIvars -
849/// This routine collect synthesized ivars for the designated class.
850///
851void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
852 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000853 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
854 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000855 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
856 Ivars.push_back(Ivar);
857 }
858 // Also look into interface's protocol list for properties declared
859 // in the protocol and whose ivars are synthesized.
860 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
861 PE = OI->protocol_end(); P != PE; ++P) {
862 ObjCProtocolDecl *PD = (*P);
863 CollectProtocolSynthesizedIvars(PD, Ivars);
864 }
865}
866
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000867unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
868 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000869 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
870 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000871 if ((*I)->getPropertyIvarDecl())
872 ++count;
873
874 // Also look into nested protocols.
875 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
876 E = PD->protocol_end(); P != E; ++P)
877 count += CountProtocolSynthesizedIvars(*P);
878 return count;
879}
880
881unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
882{
883 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000884 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
885 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000886 if ((*I)->getPropertyIvarDecl())
887 ++count;
888 }
889 // Also look into interface's protocol list for properties declared
890 // in the protocol and whose ivars are synthesized.
891 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
892 PE = OI->protocol_end(); P != PE; ++P) {
893 ObjCProtocolDecl *PD = (*P);
894 count += CountProtocolSynthesizedIvars(PD);
895 }
896 return count;
897}
898
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000899/// getInterfaceLayoutImpl - Get or compute information about the
900/// layout of the given interface.
901///
902/// \param Impl - If given, also include the layout of the interface's
903/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000904const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000905ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
906 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000907 assert(!D->isForwardDecl() && "Invalid interface decl!");
908
Devang Patel44a3dde2008-06-04 21:54:36 +0000909 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000910 ObjCContainerDecl *Key =
911 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
912 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
913 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000914
Daniel Dunbar453addb2009-05-03 11:16:44 +0000915 unsigned FieldCount = D->ivar_size();
916 // Add in synthesized ivar count if laying out an implementation.
917 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000918 unsigned SynthCount = CountSynthesizedIvars(D);
919 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000920 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000921 // entry. Note we can't cache this because we simply free all
922 // entries later; however we shouldn't look up implementations
923 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000924 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000925 return getObjCLayout(D, 0);
926 }
927
Devang Patel6a5a34c2008-06-06 02:14:01 +0000928 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000929 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000930 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
931 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000932
Daniel Dunbar913af352009-05-07 21:58:26 +0000933 // We start laying out ivars not at the end of the superclass
934 // structure, but at the next byte following the last field.
935 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000936
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000937 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000938 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000939 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000940 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000941 NewEntry->InitializeLayout(FieldCount);
942 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000943
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000944 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000945 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000946 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000947
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000948 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000949 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
950 AA->getAlignment()));
951
952 // Layout each ivar sequentially.
953 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000954 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
955 ShallowCollectObjCIvars(D, Ivars, Impl);
956 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
957 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
958
Devang Patel44a3dde2008-06-04 21:54:36 +0000959 // Finally, round the size of the total struct up to the alignment of the
960 // struct itself.
961 NewEntry->FinalizeLayout();
962 return *NewEntry;
963}
964
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000965const ASTRecordLayout &
966ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
967 return getObjCLayout(D, 0);
968}
969
970const ASTRecordLayout &
971ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
972 return getObjCLayout(D->getClassInterface(), D);
973}
974
Devang Patel88a981b2007-11-01 19:11:01 +0000975/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000976/// specified record (struct/union/class), which indicates its size and field
977/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000978const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000979 D = D->getDefinition(*this);
980 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000981
Chris Lattner464175b2007-07-18 17:52:12 +0000982 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000983 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000984 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000985
Devang Patel88a981b2007-11-01 19:11:01 +0000986 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
987 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
988 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000989 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000990
Douglas Gregore267ff32008-12-11 20:41:00 +0000991 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000992 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000993 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000994
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000995 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000996 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000997 StructPacking = PA->getAlignment();
998
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000999 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +00001000 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1001 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001002
Eli Friedman4bd998b2008-05-30 09:31:38 +00001003 // Layout each field, for now, just sequentially, respecting alignment. In
1004 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001005 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001006 for (RecordDecl::field_iterator Field = D->field_begin(),
1007 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001008 Field != FieldEnd; (void)++Field, ++FieldIdx)
1009 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001010
1011 // Finally, round the size of the total struct up to the alignment of the
1012 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001013 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001014 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001015}
1016
Chris Lattnera7674d82007-07-13 22:13:22 +00001017//===----------------------------------------------------------------------===//
1018// Type creation/memoization methods
1019//===----------------------------------------------------------------------===//
1020
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001021QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001022 QualType CanT = getCanonicalType(T);
1023 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001024 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001025
1026 // If we are composing extended qualifiers together, merge together into one
1027 // ExtQualType node.
1028 unsigned CVRQuals = T.getCVRQualifiers();
1029 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1030 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001031
Chris Lattnerb7d25532009-02-18 22:53:11 +00001032 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1033 // If this type already has an address space specified, it cannot get
1034 // another one.
1035 assert(EQT->getAddressSpace() == 0 &&
1036 "Type cannot be in multiple addr spaces!");
1037 GCAttr = EQT->getObjCGCAttr();
1038 TypeNode = EQT->getBaseType();
1039 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001040
Chris Lattnerb7d25532009-02-18 22:53:11 +00001041 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001042 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001043 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001044 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001045 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001046 return QualType(EXTQy, CVRQuals);
1047
Christopher Lambebb97e92008-02-04 02:31:56 +00001048 // If the base type isn't canonical, this won't be a canonical type either,
1049 // so fill in the canonical type field.
1050 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001051 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001052 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001053
Chris Lattnerb7d25532009-02-18 22:53:11 +00001054 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001055 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001056 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001057 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001058 ExtQualType *New =
1059 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001060 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001061 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001062 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001063}
1064
Chris Lattnerb7d25532009-02-18 22:53:11 +00001065QualType ASTContext::getObjCGCQualType(QualType T,
1066 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001067 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001068 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001069 return T;
1070
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001071 if (T->isPointerType()) {
1072 QualType Pointee = T->getAsPointerType()->getPointeeType();
1073 if (Pointee->isPointerType()) {
1074 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1075 return getPointerType(ResultType);
1076 }
1077 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001078 // If we are composing extended qualifiers together, merge together into one
1079 // ExtQualType node.
1080 unsigned CVRQuals = T.getCVRQualifiers();
1081 Type *TypeNode = T.getTypePtr();
1082 unsigned AddressSpace = 0;
1083
1084 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1085 // If this type already has an address space specified, it cannot get
1086 // another one.
1087 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1088 "Type cannot be in multiple addr spaces!");
1089 AddressSpace = EQT->getAddressSpace();
1090 TypeNode = EQT->getBaseType();
1091 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001092
1093 // Check if we've already instantiated an gc qual'd type of this type.
1094 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001095 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001096 void *InsertPos = 0;
1097 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001098 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001099
1100 // If the base type isn't canonical, this won't be a canonical type either,
1101 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001102 // FIXME: Isn't this also not canonical if the base type is a array
1103 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001104 QualType Canonical;
1105 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001106 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001107
Chris Lattnerb7d25532009-02-18 22:53:11 +00001108 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001109 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1110 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1111 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001112 ExtQualType *New =
1113 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001114 ExtQualTypes.InsertNode(New, InsertPos);
1115 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001116 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001117}
Chris Lattnera7674d82007-07-13 22:13:22 +00001118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119/// getComplexType - Return the uniqued reference to the type for a complex
1120/// number with the specified element type.
1121QualType ASTContext::getComplexType(QualType T) {
1122 // Unique pointers, to guarantee there is only one pointer of a particular
1123 // structure.
1124 llvm::FoldingSetNodeID ID;
1125 ComplexType::Profile(ID, T);
1126
1127 void *InsertPos = 0;
1128 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1129 return QualType(CT, 0);
1130
1131 // If the pointee type isn't canonical, this won't be a canonical type either,
1132 // so fill in the canonical type field.
1133 QualType Canonical;
1134 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001135 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001136
1137 // Get the new insert position for the node we care about.
1138 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001139 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 }
Steve Narofff83820b2009-01-27 22:08:43 +00001141 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 Types.push_back(New);
1143 ComplexTypes.InsertNode(New, InsertPos);
1144 return QualType(New, 0);
1145}
1146
Eli Friedmanf98aba32009-02-13 02:31:07 +00001147QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1148 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1149 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1150 FixedWidthIntType *&Entry = Map[Width];
1151 if (!Entry)
1152 Entry = new FixedWidthIntType(Width, Signed);
1153 return QualType(Entry, 0);
1154}
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
1156/// getPointerType - Return the uniqued reference to the type for a pointer to
1157/// the specified type.
1158QualType ASTContext::getPointerType(QualType T) {
1159 // Unique pointers, to guarantee there is only one pointer of a particular
1160 // structure.
1161 llvm::FoldingSetNodeID ID;
1162 PointerType::Profile(ID, T);
1163
1164 void *InsertPos = 0;
1165 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1166 return QualType(PT, 0);
1167
1168 // If the pointee type isn't canonical, this won't be a canonical type either,
1169 // so fill in the canonical type field.
1170 QualType Canonical;
1171 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001172 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 // Get the new insert position for the node we care about.
1175 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001176 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 }
Steve Narofff83820b2009-01-27 22:08:43 +00001178 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 Types.push_back(New);
1180 PointerTypes.InsertNode(New, InsertPos);
1181 return QualType(New, 0);
1182}
1183
Steve Naroff5618bd42008-08-27 16:04:49 +00001184/// getBlockPointerType - Return the uniqued reference to the type for
1185/// a pointer to the specified block.
1186QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001187 assert(T->isFunctionType() && "block of function types only");
1188 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001189 // structure.
1190 llvm::FoldingSetNodeID ID;
1191 BlockPointerType::Profile(ID, T);
1192
1193 void *InsertPos = 0;
1194 if (BlockPointerType *PT =
1195 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1196 return QualType(PT, 0);
1197
Steve Naroff296e8d52008-08-28 19:20:44 +00001198 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001199 // type either so fill in the canonical type field.
1200 QualType Canonical;
1201 if (!T->isCanonical()) {
1202 Canonical = getBlockPointerType(getCanonicalType(T));
1203
1204 // Get the new insert position for the node we care about.
1205 BlockPointerType *NewIP =
1206 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001207 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001208 }
Steve Narofff83820b2009-01-27 22:08:43 +00001209 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001210 Types.push_back(New);
1211 BlockPointerTypes.InsertNode(New, InsertPos);
1212 return QualType(New, 0);
1213}
1214
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001215/// getLValueReferenceType - Return the uniqued reference to the type for an
1216/// lvalue reference to the specified type.
1217QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // Unique pointers, to guarantee there is only one pointer of a particular
1219 // structure.
1220 llvm::FoldingSetNodeID ID;
1221 ReferenceType::Profile(ID, T);
1222
1223 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001224 if (LValueReferenceType *RT =
1225 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 // If the referencee type isn't canonical, this won't be a canonical type
1229 // either, so fill in the canonical type field.
1230 QualType Canonical;
1231 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001232 Canonical = getLValueReferenceType(getCanonicalType(T));
1233
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001235 LValueReferenceType *NewIP =
1236 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001237 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 }
1239
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001240 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001242 LValueReferenceTypes.InsertNode(New, InsertPos);
1243 return QualType(New, 0);
1244}
1245
1246/// getRValueReferenceType - Return the uniqued reference to the type for an
1247/// rvalue reference to the specified type.
1248QualType ASTContext::getRValueReferenceType(QualType T) {
1249 // Unique pointers, to guarantee there is only one pointer of a particular
1250 // structure.
1251 llvm::FoldingSetNodeID ID;
1252 ReferenceType::Profile(ID, T);
1253
1254 void *InsertPos = 0;
1255 if (RValueReferenceType *RT =
1256 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1257 return QualType(RT, 0);
1258
1259 // If the referencee type isn't canonical, this won't be a canonical type
1260 // either, so fill in the canonical type field.
1261 QualType Canonical;
1262 if (!T->isCanonical()) {
1263 Canonical = getRValueReferenceType(getCanonicalType(T));
1264
1265 // Get the new insert position for the node we care about.
1266 RValueReferenceType *NewIP =
1267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1269 }
1270
1271 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1272 Types.push_back(New);
1273 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 return QualType(New, 0);
1275}
1276
Sebastian Redlf30208a2009-01-24 21:16:55 +00001277/// getMemberPointerType - Return the uniqued reference to the type for a
1278/// member pointer to the specified type, in the specified class.
1279QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1280{
1281 // Unique pointers, to guarantee there is only one pointer of a particular
1282 // structure.
1283 llvm::FoldingSetNodeID ID;
1284 MemberPointerType::Profile(ID, T, Cls);
1285
1286 void *InsertPos = 0;
1287 if (MemberPointerType *PT =
1288 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1289 return QualType(PT, 0);
1290
1291 // If the pointee or class type isn't canonical, this won't be a canonical
1292 // type either, so fill in the canonical type field.
1293 QualType Canonical;
1294 if (!T->isCanonical()) {
1295 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1296
1297 // Get the new insert position for the node we care about.
1298 MemberPointerType *NewIP =
1299 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1300 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1301 }
Steve Narofff83820b2009-01-27 22:08:43 +00001302 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001303 Types.push_back(New);
1304 MemberPointerTypes.InsertNode(New, InsertPos);
1305 return QualType(New, 0);
1306}
1307
Steve Narofffb22d962007-08-30 01:06:46 +00001308/// getConstantArrayType - Return the unique reference to the type for an
1309/// array of the specified element type.
1310QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001311 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001312 ArrayType::ArraySizeModifier ASM,
1313 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001314 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1315 "Constant array of VLAs is illegal!");
1316
Chris Lattner38aeec72009-05-13 04:12:56 +00001317 // Convert the array size into a canonical width matching the pointer size for
1318 // the target.
1319 llvm::APInt ArySize(ArySizeIn);
1320 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1321
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001323 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001324
1325 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001326 if (ConstantArrayType *ATP =
1327 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 return QualType(ATP, 0);
1329
1330 // If the element type isn't canonical, this won't be a canonical type either,
1331 // so fill in the canonical type field.
1332 QualType Canonical;
1333 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001334 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001335 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001337 ConstantArrayType *NewIP =
1338 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001339 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 }
1341
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001342 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001343 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001344 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 Types.push_back(New);
1346 return QualType(New, 0);
1347}
1348
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001349/// getConstantArrayWithExprType - Return a reference to the type for
1350/// an array of the specified element type.
1351QualType
1352ASTContext::getConstantArrayWithExprType(QualType EltTy,
1353 const llvm::APInt &ArySizeIn,
1354 Expr *ArySizeExpr,
1355 ArrayType::ArraySizeModifier ASM,
1356 unsigned EltTypeQuals,
1357 SourceRange Brackets) {
1358 // Convert the array size into a canonical width matching the pointer
1359 // size for the target.
1360 llvm::APInt ArySize(ArySizeIn);
1361 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1362
1363 // Compute the canonical ConstantArrayType.
1364 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1365 ArySize, ASM, EltTypeQuals);
1366 // Since we don't unique expressions, it isn't possible to unique VLA's
1367 // that have an expression provided for their size.
1368 ConstantArrayWithExprType *New =
1369 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1370 ArySize, ArySizeExpr,
1371 ASM, EltTypeQuals, Brackets);
1372 Types.push_back(New);
1373 return QualType(New, 0);
1374}
1375
1376/// getConstantArrayWithoutExprType - Return a reference to the type for
1377/// an array of the specified element type.
1378QualType
1379ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1380 const llvm::APInt &ArySizeIn,
1381 ArrayType::ArraySizeModifier ASM,
1382 unsigned EltTypeQuals) {
1383 // Convert the array size into a canonical width matching the pointer
1384 // size for the target.
1385 llvm::APInt ArySize(ArySizeIn);
1386 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1387
1388 // Compute the canonical ConstantArrayType.
1389 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1390 ArySize, ASM, EltTypeQuals);
1391 ConstantArrayWithoutExprType *New =
1392 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1393 ArySize, ASM, EltTypeQuals);
1394 Types.push_back(New);
1395 return QualType(New, 0);
1396}
1397
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001398/// getVariableArrayType - Returns a non-unique reference to the type for a
1399/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001400QualType ASTContext::getVariableArrayType(QualType EltTy,
1401 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001402 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001403 unsigned EltTypeQuals,
1404 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001405 // Since we don't unique expressions, it isn't possible to unique VLA's
1406 // that have an expression provided for their size.
1407
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001408 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001409 new(*this,8)VariableArrayType(EltTy, QualType(),
1410 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001411
1412 VariableArrayTypes.push_back(New);
1413 Types.push_back(New);
1414 return QualType(New, 0);
1415}
1416
Douglas Gregor898574e2008-12-05 23:32:09 +00001417/// getDependentSizedArrayType - Returns a non-unique reference to
1418/// the type for a dependently-sized array of the specified element
1419/// type. FIXME: We will need these to be uniqued, or at least
1420/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001421QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1422 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001423 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001424 unsigned EltTypeQuals,
1425 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001426 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1427 "Size must be type- or value-dependent!");
1428
1429 // Since we don't unique expressions, it isn't possible to unique
1430 // dependently-sized array types.
1431
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001432 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001433 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1434 NumElts, ASM, EltTypeQuals,
1435 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001436
1437 DependentSizedArrayTypes.push_back(New);
1438 Types.push_back(New);
1439 return QualType(New, 0);
1440}
1441
Eli Friedmanc5773c42008-02-15 18:16:39 +00001442QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1443 ArrayType::ArraySizeModifier ASM,
1444 unsigned EltTypeQuals) {
1445 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001446 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001447
1448 void *InsertPos = 0;
1449 if (IncompleteArrayType *ATP =
1450 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1451 return QualType(ATP, 0);
1452
1453 // If the element type isn't canonical, this won't be a canonical type
1454 // either, so fill in the canonical type field.
1455 QualType Canonical;
1456
1457 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001458 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001459 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001460
1461 // Get the new insert position for the node we care about.
1462 IncompleteArrayType *NewIP =
1463 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001464 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001465 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001466
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001467 IncompleteArrayType *New
1468 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1469 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001470
1471 IncompleteArrayTypes.InsertNode(New, InsertPos);
1472 Types.push_back(New);
1473 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001474}
1475
Steve Naroff73322922007-07-18 18:00:27 +00001476/// getVectorType - Return the unique reference to a vector type of
1477/// the specified element type and size. VectorType must be a built-in type.
1478QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 BuiltinType *baseType;
1480
Chris Lattnerf52ab252008-04-06 22:59:24 +00001481 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001482 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001483
1484 // Check if we've already instantiated a vector of this type.
1485 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001486 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 void *InsertPos = 0;
1488 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(VTP, 0);
1490
1491 // If the element type isn't canonical, this won't be a canonical type either,
1492 // so fill in the canonical type field.
1493 QualType Canonical;
1494 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001495 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496
1497 // Get the new insert position for the node we care about.
1498 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001499 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 }
Steve Narofff83820b2009-01-27 22:08:43 +00001501 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 VectorTypes.InsertNode(New, InsertPos);
1503 Types.push_back(New);
1504 return QualType(New, 0);
1505}
1506
Nate Begeman213541a2008-04-18 23:10:10 +00001507/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001508/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001509QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001510 BuiltinType *baseType;
1511
Chris Lattnerf52ab252008-04-06 22:59:24 +00001512 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001513 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001514
1515 // Check if we've already instantiated a vector of this type.
1516 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001517 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001518 void *InsertPos = 0;
1519 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1520 return QualType(VTP, 0);
1521
1522 // If the element type isn't canonical, this won't be a canonical type either,
1523 // so fill in the canonical type field.
1524 QualType Canonical;
1525 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001526 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001527
1528 // Get the new insert position for the node we care about.
1529 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001530 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001531 }
Steve Narofff83820b2009-01-27 22:08:43 +00001532 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001533 VectorTypes.InsertNode(New, InsertPos);
1534 Types.push_back(New);
1535 return QualType(New, 0);
1536}
1537
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001538QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1539 Expr *SizeExpr,
1540 SourceLocation AttrLoc) {
1541 DependentSizedExtVectorType *New =
1542 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1543 SizeExpr, AttrLoc);
1544
1545 DependentSizedExtVectorTypes.push_back(New);
1546 Types.push_back(New);
1547 return QualType(New, 0);
1548}
1549
Douglas Gregor72564e72009-02-26 23:50:07 +00001550/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001551///
Douglas Gregor72564e72009-02-26 23:50:07 +00001552QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 // Unique functions, to guarantee there is only one function of a particular
1554 // structure.
1555 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001556 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557
1558 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001559 if (FunctionNoProtoType *FT =
1560 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 return QualType(FT, 0);
1562
1563 QualType Canonical;
1564 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001565 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001566
1567 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001568 FunctionNoProtoType *NewIP =
1569 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001570 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 }
1572
Douglas Gregor72564e72009-02-26 23:50:07 +00001573 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001575 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 return QualType(New, 0);
1577}
1578
1579/// getFunctionType - Return a normal function type with a typed argument
1580/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001581QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001582 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001583 unsigned TypeQuals, bool hasExceptionSpec,
1584 bool hasAnyExceptionSpec, unsigned NumExs,
1585 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // Unique functions, to guarantee there is only one function of a particular
1587 // structure.
1588 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001589 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001590 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1591 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592
1593 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001594 if (FunctionProtoType *FTP =
1595 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001597
1598 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001600 if (hasExceptionSpec)
1601 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1603 if (!ArgArray[i]->isCanonical())
1604 isCanonical = false;
1605
1606 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001607 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 QualType Canonical;
1609 if (!isCanonical) {
1610 llvm::SmallVector<QualType, 16> CanonicalArgs;
1611 CanonicalArgs.reserve(NumArgs);
1612 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001613 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001614
Chris Lattnerf52ab252008-04-06 22:59:24 +00001615 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001616 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001617 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001618
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001620 FunctionProtoType *NewIP =
1621 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001622 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001624
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001626 // for two variable size arrays (for parameter and exception types) at the
1627 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001628 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001629 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1630 NumArgs*sizeof(QualType) +
1631 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001632 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001633 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1634 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001636 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 return QualType(FTP, 0);
1638}
1639
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001640/// getTypeDeclType - Return the unique reference to the type for the
1641/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001642QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001643 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001644 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1645
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001646 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001647 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001648 else if (isa<TemplateTypeParmDecl>(Decl)) {
1649 assert(false && "Template type parameter types are always available.");
1650 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001651 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001652
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001653 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001654 if (PrevDecl)
1655 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001656 else
1657 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001658 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001659 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1660 if (PrevDecl)
1661 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001662 else
1663 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001664 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001665 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001666 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001667
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001668 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001669 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001670}
1671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672/// getTypedefType - Return the unique reference to the type for the
1673/// specified typename decl.
1674QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1675 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1676
Chris Lattnerf52ab252008-04-06 22:59:24 +00001677 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001678 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 Types.push_back(Decl->TypeForDecl);
1680 return QualType(Decl->TypeForDecl, 0);
1681}
1682
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001683/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001684/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001685QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001686 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1687
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001688 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1689 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001690 Types.push_back(Decl->TypeForDecl);
1691 return QualType(Decl->TypeForDecl, 0);
1692}
1693
Douglas Gregorfab9d672009-02-05 23:33:38 +00001694/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001695/// parameter or parameter pack with the given depth, index, and (optionally)
1696/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001697QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001698 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001699 IdentifierInfo *Name) {
1700 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001701 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001702 void *InsertPos = 0;
1703 TemplateTypeParmType *TypeParm
1704 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1705
1706 if (TypeParm)
1707 return QualType(TypeParm, 0);
1708
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001709 if (Name) {
1710 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1711 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1712 Name, Canon);
1713 } else
1714 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001715
1716 Types.push_back(TypeParm);
1717 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1718
1719 return QualType(TypeParm, 0);
1720}
1721
Douglas Gregor55f6b142009-02-09 18:46:07 +00001722QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001723ASTContext::getTemplateSpecializationType(TemplateName Template,
1724 const TemplateArgument *Args,
1725 unsigned NumArgs,
1726 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001727 if (!Canon.isNull())
1728 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001729
Douglas Gregor55f6b142009-02-09 18:46:07 +00001730 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001731 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001732
Douglas Gregor55f6b142009-02-09 18:46:07 +00001733 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001734 TemplateSpecializationType *Spec
1735 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001736
1737 if (Spec)
1738 return QualType(Spec, 0);
1739
Douglas Gregor7532dc62009-03-30 22:58:21 +00001740 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001741 sizeof(TemplateArgument) * NumArgs),
1742 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001743 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001744 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001745 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001746
1747 return QualType(Spec, 0);
1748}
1749
Douglas Gregore4e5b052009-03-19 00:18:19 +00001750QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001751ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001752 QualType NamedType) {
1753 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001754 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001755
1756 void *InsertPos = 0;
1757 QualifiedNameType *T
1758 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1759 if (T)
1760 return QualType(T, 0);
1761
Douglas Gregorab452ba2009-03-26 23:50:42 +00001762 T = new (*this) QualifiedNameType(NNS, NamedType,
1763 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001764 Types.push_back(T);
1765 QualifiedNameTypes.InsertNode(T, InsertPos);
1766 return QualType(T, 0);
1767}
1768
Douglas Gregord57959a2009-03-27 23:10:48 +00001769QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1770 const IdentifierInfo *Name,
1771 QualType Canon) {
1772 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1773
1774 if (Canon.isNull()) {
1775 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1776 if (CanonNNS != NNS)
1777 Canon = getTypenameType(CanonNNS, Name);
1778 }
1779
1780 llvm::FoldingSetNodeID ID;
1781 TypenameType::Profile(ID, NNS, Name);
1782
1783 void *InsertPos = 0;
1784 TypenameType *T
1785 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1786 if (T)
1787 return QualType(T, 0);
1788
1789 T = new (*this) TypenameType(NNS, Name, Canon);
1790 Types.push_back(T);
1791 TypenameTypes.InsertNode(T, InsertPos);
1792 return QualType(T, 0);
1793}
1794
Douglas Gregor17343172009-04-01 00:28:59 +00001795QualType
1796ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1797 const TemplateSpecializationType *TemplateId,
1798 QualType Canon) {
1799 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1800
1801 if (Canon.isNull()) {
1802 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1803 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1804 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1805 const TemplateSpecializationType *CanonTemplateId
1806 = CanonType->getAsTemplateSpecializationType();
1807 assert(CanonTemplateId &&
1808 "Canonical type must also be a template specialization type");
1809 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1810 }
1811 }
1812
1813 llvm::FoldingSetNodeID ID;
1814 TypenameType::Profile(ID, NNS, TemplateId);
1815
1816 void *InsertPos = 0;
1817 TypenameType *T
1818 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1819 if (T)
1820 return QualType(T, 0);
1821
1822 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1823 Types.push_back(T);
1824 TypenameTypes.InsertNode(T, InsertPos);
1825 return QualType(T, 0);
1826}
1827
Chris Lattner88cb27a2008-04-07 04:56:42 +00001828/// CmpProtocolNames - Comparison predicate for sorting protocols
1829/// alphabetically.
1830static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1831 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001832 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001833}
1834
1835static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1836 unsigned &NumProtocols) {
1837 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1838
1839 // Sort protocols, keyed by name.
1840 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1841
1842 // Remove duplicates.
1843 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1844 NumProtocols = ProtocolsEnd-Protocols;
1845}
1846
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001847/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1848/// the given interface decl and the conforming protocol list.
1849QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1850 ObjCProtocolDecl **Protocols,
1851 unsigned NumProtocols) {
1852 // Sort the protocol list alphabetically to canonicalize it.
1853 if (NumProtocols)
1854 SortAndUniqueProtocols(Protocols, NumProtocols);
1855
1856 llvm::FoldingSetNodeID ID;
1857 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1858
1859 void *InsertPos = 0;
1860 if (ObjCObjectPointerType *QT =
1861 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1862 return QualType(QT, 0);
1863
1864 // No Match;
1865 ObjCObjectPointerType *QType =
1866 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1867
1868 Types.push_back(QType);
1869 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1870 return QualType(QType, 0);
1871}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001872
Chris Lattner065f0d72008-04-07 04:44:08 +00001873/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1874/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001875QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1876 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001877 // Sort the protocol list alphabetically to canonicalize it.
1878 SortAndUniqueProtocols(Protocols, NumProtocols);
1879
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001880 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001881 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001882
1883 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 if (ObjCQualifiedInterfaceType *QT =
1885 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001886 return QualType(QT, 0);
1887
1888 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001889 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001890 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001891
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001892 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001893 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001894 return QualType(QType, 0);
1895}
1896
Douglas Gregor72564e72009-02-26 23:50:07 +00001897/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1898/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001899/// multiple declarations that refer to "typeof(x)" all contain different
1900/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1901/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001902QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001903 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001904 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001905 Types.push_back(toe);
1906 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001907}
1908
Steve Naroff9752f252007-08-01 18:02:17 +00001909/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1910/// TypeOfType AST's. The only motivation to unique these nodes would be
1911/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1912/// an issue. This doesn't effect the type checker, since it operates
1913/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001914QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001915 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001916 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001917 Types.push_back(tot);
1918 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001919}
1920
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001921/// getDecltypeForExpr - Given an expr, will return the decltype for that
1922/// expression, according to the rules in C++0x [dcl.type.simple]p4
1923static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001924 if (e->isTypeDependent())
1925 return Context.DependentTy;
1926
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001927 // If e is an id expression or a class member access, decltype(e) is defined
1928 // as the type of the entity named by e.
1929 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1930 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1931 return VD->getType();
1932 }
1933 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1934 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1935 return FD->getType();
1936 }
1937 // If e is a function call or an invocation of an overloaded operator,
1938 // (parentheses around e are ignored), decltype(e) is defined as the
1939 // return type of that function.
1940 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1941 return CE->getCallReturnType();
1942
1943 QualType T = e->getType();
1944
1945 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1946 // defined as T&, otherwise decltype(e) is defined as T.
1947 if (e->isLvalue(Context) == Expr::LV_Valid)
1948 T = Context.getLValueReferenceType(T);
1949
1950 return T;
1951}
1952
Anders Carlsson395b4752009-06-24 19:06:50 +00001953/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1954/// DecltypeType AST's. The only motivation to unique these nodes would be
1955/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1956/// an issue. This doesn't effect the type checker, since it operates
1957/// on canonical type's (which are always unique).
1958QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001959 QualType T = getDecltypeForExpr(e, *this);
1960 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001961 Types.push_back(dt);
1962 return QualType(dt, 0);
1963}
1964
Reid Spencer5f016e22007-07-11 17:01:13 +00001965/// getTagDeclType - Return the unique reference to the type for the
1966/// specified TagDecl (struct/union/class/enum) decl.
1967QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001968 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001969 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001970}
1971
1972/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1973/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1974/// needs to agree with the definition in <stddef.h>.
1975QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001976 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001977}
1978
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001979/// getSignedWCharType - Return the type of "signed wchar_t".
1980/// Used when in C++, as a GCC extension.
1981QualType ASTContext::getSignedWCharType() const {
1982 // FIXME: derive from "Target" ?
1983 return WCharTy;
1984}
1985
1986/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1987/// Used when in C++, as a GCC extension.
1988QualType ASTContext::getUnsignedWCharType() const {
1989 // FIXME: derive from "Target" ?
1990 return UnsignedIntTy;
1991}
1992
Chris Lattner8b9023b2007-07-13 03:05:23 +00001993/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1994/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1995QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001996 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001997}
1998
Chris Lattnere6327742008-04-02 05:18:44 +00001999//===----------------------------------------------------------------------===//
2000// Type Operators
2001//===----------------------------------------------------------------------===//
2002
Chris Lattner77c96472008-04-06 22:41:35 +00002003/// getCanonicalType - Return the canonical (structural) type corresponding to
2004/// the specified potentially non-canonical type. The non-canonical version
2005/// of a type may have many "decorated" versions of types. Decorators can
2006/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2007/// to be free of any of these, allowing two canonical types to be compared
2008/// for exact equality with a simple pointer comparison.
2009QualType ASTContext::getCanonicalType(QualType T) {
2010 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002011
2012 // If the result has type qualifiers, make sure to canonicalize them as well.
2013 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2014 if (TypeQuals == 0) return CanType;
2015
2016 // If the type qualifiers are on an array type, get the canonical type of the
2017 // array with the qualifiers applied to the element type.
2018 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2019 if (!AT)
2020 return CanType.getQualifiedType(TypeQuals);
2021
2022 // Get the canonical version of the element with the extra qualifiers on it.
2023 // This can recursively sink qualifiers through multiple levels of arrays.
2024 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2025 NewEltTy = getCanonicalType(NewEltTy);
2026
2027 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2028 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2029 CAT->getIndexTypeQualifier());
2030 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2031 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2032 IAT->getIndexTypeQualifier());
2033
Douglas Gregor898574e2008-12-05 23:32:09 +00002034 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002035 return getDependentSizedArrayType(NewEltTy,
2036 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002037 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002038 DSAT->getIndexTypeQualifier(),
2039 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002040
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002041 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002042 return getVariableArrayType(NewEltTy,
2043 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002044 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002045 VAT->getIndexTypeQualifier(),
2046 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002047}
2048
Douglas Gregor7da97d02009-05-10 22:57:19 +00002049Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00002050 if (!D)
2051 return 0;
2052
Douglas Gregor7da97d02009-05-10 22:57:19 +00002053 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2054 QualType T = getTagDeclType(Tag);
2055 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2056 ->getDecl());
2057 }
2058
2059 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2060 while (Template->getPreviousDeclaration())
2061 Template = Template->getPreviousDeclaration();
2062 return Template;
2063 }
2064
2065 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2066 while (Function->getPreviousDeclaration())
2067 Function = Function->getPreviousDeclaration();
2068 return const_cast<FunctionDecl *>(Function);
2069 }
2070
Douglas Gregor127102b2009-06-29 20:59:39 +00002071 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2072 while (FunTmpl->getPreviousDeclaration())
2073 FunTmpl = FunTmpl->getPreviousDeclaration();
2074 return FunTmpl;
2075 }
2076
Douglas Gregor7da97d02009-05-10 22:57:19 +00002077 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2078 while (Var->getPreviousDeclaration())
2079 Var = Var->getPreviousDeclaration();
2080 return const_cast<VarDecl *>(Var);
2081 }
2082
2083 return D;
2084}
2085
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002086TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2087 // If this template name refers to a template, the canonical
2088 // template name merely stores the template itself.
2089 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002090 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002091
2092 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2093 assert(DTN && "Non-dependent template names must refer to template decls.");
2094 return DTN->CanonicalTemplateName;
2095}
2096
Douglas Gregord57959a2009-03-27 23:10:48 +00002097NestedNameSpecifier *
2098ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2099 if (!NNS)
2100 return 0;
2101
2102 switch (NNS->getKind()) {
2103 case NestedNameSpecifier::Identifier:
2104 // Canonicalize the prefix but keep the identifier the same.
2105 return NestedNameSpecifier::Create(*this,
2106 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2107 NNS->getAsIdentifier());
2108
2109 case NestedNameSpecifier::Namespace:
2110 // A namespace is canonical; build a nested-name-specifier with
2111 // this namespace and no prefix.
2112 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2113
2114 case NestedNameSpecifier::TypeSpec:
2115 case NestedNameSpecifier::TypeSpecWithTemplate: {
2116 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2117 NestedNameSpecifier *Prefix = 0;
2118
2119 // FIXME: This isn't the right check!
2120 if (T->isDependentType())
2121 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2122
2123 return NestedNameSpecifier::Create(*this, Prefix,
2124 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2125 T.getTypePtr());
2126 }
2127
2128 case NestedNameSpecifier::Global:
2129 // The global specifier is canonical and unique.
2130 return NNS;
2131 }
2132
2133 // Required to silence a GCC warning
2134 return 0;
2135}
2136
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002137
2138const ArrayType *ASTContext::getAsArrayType(QualType T) {
2139 // Handle the non-qualified case efficiently.
2140 if (T.getCVRQualifiers() == 0) {
2141 // Handle the common positive case fast.
2142 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2143 return AT;
2144 }
2145
2146 // Handle the common negative case fast, ignoring CVR qualifiers.
2147 QualType CType = T->getCanonicalTypeInternal();
2148
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002149 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002150 // test.
2151 if (!isa<ArrayType>(CType) &&
2152 !isa<ArrayType>(CType.getUnqualifiedType()))
2153 return 0;
2154
2155 // Apply any CVR qualifiers from the array type to the element type. This
2156 // implements C99 6.7.3p8: "If the specification of an array type includes
2157 // any type qualifiers, the element type is so qualified, not the array type."
2158
2159 // If we get here, we either have type qualifiers on the type, or we have
2160 // sugar such as a typedef in the way. If we have type qualifiers on the type
2161 // we must propagate them down into the elemeng type.
2162 unsigned CVRQuals = T.getCVRQualifiers();
2163 unsigned AddrSpace = 0;
2164 Type *Ty = T.getTypePtr();
2165
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002166 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002167 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002168 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2169 AddrSpace = EXTQT->getAddressSpace();
2170 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002171 } else {
2172 T = Ty->getDesugaredType();
2173 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2174 break;
2175 CVRQuals |= T.getCVRQualifiers();
2176 Ty = T.getTypePtr();
2177 }
2178 }
2179
2180 // If we have a simple case, just return now.
2181 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2182 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2183 return ATy;
2184
2185 // Otherwise, we have an array and we have qualifiers on it. Push the
2186 // qualifiers into the array element type and return a new array type.
2187 // Get the canonical version of the element with the extra qualifiers on it.
2188 // This can recursively sink qualifiers through multiple levels of arrays.
2189 QualType NewEltTy = ATy->getElementType();
2190 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002191 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002192 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2193
2194 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2195 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2196 CAT->getSizeModifier(),
2197 CAT->getIndexTypeQualifier()));
2198 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2199 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2200 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002201 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002202
Douglas Gregor898574e2008-12-05 23:32:09 +00002203 if (const DependentSizedArrayType *DSAT
2204 = dyn_cast<DependentSizedArrayType>(ATy))
2205 return cast<ArrayType>(
2206 getDependentSizedArrayType(NewEltTy,
2207 DSAT->getSizeExpr(),
2208 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002209 DSAT->getIndexTypeQualifier(),
2210 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002211
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002212 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002213 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2214 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002215 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002216 VAT->getIndexTypeQualifier(),
2217 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002218}
2219
2220
Chris Lattnere6327742008-04-02 05:18:44 +00002221/// getArrayDecayedType - Return the properly qualified result of decaying the
2222/// specified array type to a pointer. This operation is non-trivial when
2223/// handling typedefs etc. The canonical type of "T" must be an array type,
2224/// this returns a pointer to a properly qualified element of the array.
2225///
2226/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2227QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002228 // Get the element type with 'getAsArrayType' so that we don't lose any
2229 // typedefs in the element type of the array. This also handles propagation
2230 // of type qualifiers from the array type into the element type if present
2231 // (C99 6.7.3p8).
2232 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2233 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002234
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002235 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002236
2237 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002238 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002239}
2240
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002241QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002242 QualType ElemTy = VAT->getElementType();
2243
2244 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2245 return getBaseElementType(VAT);
2246
2247 return ElemTy;
2248}
2249
Reid Spencer5f016e22007-07-11 17:01:13 +00002250/// getFloatingRank - Return a relative rank for floating point types.
2251/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002252static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002253 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002255
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002256 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002257 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002258 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 case BuiltinType::Float: return FloatRank;
2260 case BuiltinType::Double: return DoubleRank;
2261 case BuiltinType::LongDouble: return LongDoubleRank;
2262 }
2263}
2264
Steve Naroff716c7302007-08-27 01:41:48 +00002265/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2266/// point or a complex type (based on typeDomain/typeSize).
2267/// 'typeDomain' is a real floating point or complex type.
2268/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002269QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2270 QualType Domain) const {
2271 FloatingRank EltRank = getFloatingRank(Size);
2272 if (Domain->isComplexType()) {
2273 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002274 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002275 case FloatRank: return FloatComplexTy;
2276 case DoubleRank: return DoubleComplexTy;
2277 case LongDoubleRank: return LongDoubleComplexTy;
2278 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 }
Chris Lattner1361b112008-04-06 23:58:54 +00002280
2281 assert(Domain->isRealFloatingType() && "Unknown domain!");
2282 switch (EltRank) {
2283 default: assert(0 && "getFloatingRank(): illegal value for rank");
2284 case FloatRank: return FloatTy;
2285 case DoubleRank: return DoubleTy;
2286 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002287 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002288}
2289
Chris Lattner7cfeb082008-04-06 23:55:33 +00002290/// getFloatingTypeOrder - Compare the rank of the two specified floating
2291/// point types, ignoring the domain of the type (i.e. 'double' ==
2292/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2293/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002294int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2295 FloatingRank LHSR = getFloatingRank(LHS);
2296 FloatingRank RHSR = getFloatingRank(RHS);
2297
2298 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002299 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002300 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002301 return 1;
2302 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002303}
2304
Chris Lattnerf52ab252008-04-06 22:59:24 +00002305/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2306/// routine will assert if passed a built-in type that isn't an integer or enum,
2307/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002308unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002309 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002310 if (EnumType* ET = dyn_cast<EnumType>(T))
2311 T = ET->getDecl()->getIntegerType().getTypePtr();
2312
Eli Friedmana3426752009-07-05 23:44:27 +00002313 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2314 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2315
Eli Friedmanf98aba32009-02-13 02:31:07 +00002316 // There are two things which impact the integer rank: the width, and
2317 // the ordering of builtins. The builtin ordering is encoded in the
2318 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002319 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002320 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002321
Chris Lattnerf52ab252008-04-06 22:59:24 +00002322 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002323 default: assert(0 && "getIntegerRank(): not a built-in integer");
2324 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002325 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002326 case BuiltinType::Char_S:
2327 case BuiltinType::Char_U:
2328 case BuiltinType::SChar:
2329 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002330 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002331 case BuiltinType::Short:
2332 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002333 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002334 case BuiltinType::Int:
2335 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002336 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002337 case BuiltinType::Long:
2338 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002339 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002340 case BuiltinType::LongLong:
2341 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002342 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002343 case BuiltinType::Int128:
2344 case BuiltinType::UInt128:
2345 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002346 }
2347}
2348
Chris Lattner7cfeb082008-04-06 23:55:33 +00002349/// getIntegerTypeOrder - Returns the highest ranked integer type:
2350/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2351/// LHS < RHS, return -1.
2352int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002353 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2354 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002355 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002356
Chris Lattnerf52ab252008-04-06 22:59:24 +00002357 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2358 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002359
Chris Lattner7cfeb082008-04-06 23:55:33 +00002360 unsigned LHSRank = getIntegerRank(LHSC);
2361 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002362
Chris Lattner7cfeb082008-04-06 23:55:33 +00002363 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2364 if (LHSRank == RHSRank) return 0;
2365 return LHSRank > RHSRank ? 1 : -1;
2366 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002367
Chris Lattner7cfeb082008-04-06 23:55:33 +00002368 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2369 if (LHSUnsigned) {
2370 // If the unsigned [LHS] type is larger, return it.
2371 if (LHSRank >= RHSRank)
2372 return 1;
2373
2374 // If the signed type can represent all values of the unsigned type, it
2375 // wins. Because we are dealing with 2's complement and types that are
2376 // powers of two larger than each other, this is always safe.
2377 return -1;
2378 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002379
Chris Lattner7cfeb082008-04-06 23:55:33 +00002380 // If the unsigned [RHS] type is larger, return it.
2381 if (RHSRank >= LHSRank)
2382 return -1;
2383
2384 // If the signed type can represent all values of the unsigned type, it
2385 // wins. Because we are dealing with 2's complement and types that are
2386 // powers of two larger than each other, this is always safe.
2387 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002388}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002389
2390// getCFConstantStringType - Return the type used for constant CFStrings.
2391QualType ASTContext::getCFConstantStringType() {
2392 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002393 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002394 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002395 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002396 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002397
2398 // const int *isa;
2399 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002400 // int flags;
2401 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002402 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002403 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002404 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002405 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002406
Anders Carlsson71993dd2007-08-17 05:31:46 +00002407 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002408 for (unsigned i = 0; i < 4; ++i) {
2409 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2410 SourceLocation(), 0,
2411 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002412 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002413 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002414 }
2415
2416 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002417 }
2418
2419 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002420}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002421
Douglas Gregor319ac892009-04-23 22:29:11 +00002422void ASTContext::setCFConstantStringType(QualType T) {
2423 const RecordType *Rec = T->getAsRecordType();
2424 assert(Rec && "Invalid CFConstantStringType");
2425 CFConstantStringTypeDecl = Rec->getDecl();
2426}
2427
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002428QualType ASTContext::getObjCFastEnumerationStateType()
2429{
2430 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002431 ObjCFastEnumerationStateTypeDecl =
2432 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2433 &Idents.get("__objcFastEnumerationState"));
2434
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002435 QualType FieldTypes[] = {
2436 UnsignedLongTy,
2437 getPointerType(ObjCIdType),
2438 getPointerType(UnsignedLongTy),
2439 getConstantArrayType(UnsignedLongTy,
2440 llvm::APInt(32, 5), ArrayType::Normal, 0)
2441 };
2442
Douglas Gregor44b43212008-12-11 16:49:14 +00002443 for (size_t i = 0; i < 4; ++i) {
2444 FieldDecl *Field = FieldDecl::Create(*this,
2445 ObjCFastEnumerationStateTypeDecl,
2446 SourceLocation(), 0,
2447 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002448 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002449 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002450 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002451
Douglas Gregor44b43212008-12-11 16:49:14 +00002452 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002453 }
2454
2455 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2456}
2457
Douglas Gregor319ac892009-04-23 22:29:11 +00002458void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2459 const RecordType *Rec = T->getAsRecordType();
2460 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2461 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2462}
2463
Anders Carlssone8c49532007-10-29 06:33:42 +00002464// This returns true if a type has been typedefed to BOOL:
2465// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002466static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002467 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002468 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2469 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002470
2471 return false;
2472}
2473
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002475/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002476int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002477 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002478
2479 // Make all integer and enum types at least as large as an int
2480 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002481 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002482 // Treat arrays as pointers, since that's how they're passed in.
2483 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002484 sz = getTypeSize(VoidPtrTy);
2485 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002486}
2487
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002488/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002489/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002490void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002491 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002492 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002493 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002495 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002496 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002497 // Compute size of all parameters.
2498 // Start with computing size of a pointer in number of bytes.
2499 // FIXME: There might(should) be a better way of doing this computation!
2500 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002501 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002502 // The first two arguments (self and _cmd) are pointers; account for
2503 // their size.
2504 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002505 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2506 E = Decl->param_end(); PI != E; ++PI) {
2507 QualType PType = (*PI)->getType();
2508 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002509 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002510 ParmOffset += sz;
2511 }
2512 S += llvm::utostr(ParmOffset);
2513 S += "@0:";
2514 S += llvm::utostr(PtrSize);
2515
2516 // Argument types.
2517 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002518 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2519 E = Decl->param_end(); PI != E; ++PI) {
2520 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002521 QualType PType = PVDecl->getOriginalType();
2522 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002523 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2524 // Use array's original type only if it has known number of
2525 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002526 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002527 PType = PVDecl->getType();
2528 } else if (PType->isFunctionType())
2529 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002530 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002531 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002532 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002533 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002534 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002536 }
2537}
2538
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002539/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002540/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002541/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2542/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002543/// Property attributes are stored as a comma-delimited C string. The simple
2544/// attributes readonly and bycopy are encoded as single characters. The
2545/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2546/// encoded as single characters, followed by an identifier. Property types
2547/// are also encoded as a parametrized attribute. The characters used to encode
2548/// these attributes are defined by the following enumeration:
2549/// @code
2550/// enum PropertyAttributes {
2551/// kPropertyReadOnly = 'R', // property is read-only.
2552/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2553/// kPropertyByref = '&', // property is a reference to the value last assigned
2554/// kPropertyDynamic = 'D', // property is dynamic
2555/// kPropertyGetter = 'G', // followed by getter selector name
2556/// kPropertySetter = 'S', // followed by setter selector name
2557/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2558/// kPropertyType = 't' // followed by old-style type encoding.
2559/// kPropertyWeak = 'W' // 'weak' property
2560/// kPropertyStrong = 'P' // property GC'able
2561/// kPropertyNonAtomic = 'N' // property non-atomic
2562/// };
2563/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002564void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2565 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002566 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002567 // Collect information from the property implementation decl(s).
2568 bool Dynamic = false;
2569 ObjCPropertyImplDecl *SynthesizePID = 0;
2570
2571 // FIXME: Duplicated code due to poor abstraction.
2572 if (Container) {
2573 if (const ObjCCategoryImplDecl *CID =
2574 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2575 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002576 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002577 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002578 ObjCPropertyImplDecl *PID = *i;
2579 if (PID->getPropertyDecl() == PD) {
2580 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2581 Dynamic = true;
2582 } else {
2583 SynthesizePID = PID;
2584 }
2585 }
2586 }
2587 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002588 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002589 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002590 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002591 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002592 ObjCPropertyImplDecl *PID = *i;
2593 if (PID->getPropertyDecl() == PD) {
2594 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2595 Dynamic = true;
2596 } else {
2597 SynthesizePID = PID;
2598 }
2599 }
2600 }
2601 }
2602 }
2603
2604 // FIXME: This is not very efficient.
2605 S = "T";
2606
2607 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002608 // GCC has some special rules regarding encoding of properties which
2609 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002610 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002611 true /* outermost type */,
2612 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002613
2614 if (PD->isReadOnly()) {
2615 S += ",R";
2616 } else {
2617 switch (PD->getSetterKind()) {
2618 case ObjCPropertyDecl::Assign: break;
2619 case ObjCPropertyDecl::Copy: S += ",C"; break;
2620 case ObjCPropertyDecl::Retain: S += ",&"; break;
2621 }
2622 }
2623
2624 // It really isn't clear at all what this means, since properties
2625 // are "dynamic by default".
2626 if (Dynamic)
2627 S += ",D";
2628
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002629 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2630 S += ",N";
2631
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002632 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2633 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002634 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002635 }
2636
2637 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2638 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002639 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002640 }
2641
2642 if (SynthesizePID) {
2643 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2644 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002645 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002646 }
2647
2648 // FIXME: OBJCGC: weak & strong
2649}
2650
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002651/// getLegacyIntegralTypeEncoding -
2652/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002653/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002654/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2655///
2656void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2657 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2658 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002659 if (BT->getKind() == BuiltinType::ULong &&
2660 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002661 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002662 else
2663 if (BT->getKind() == BuiltinType::Long &&
2664 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002665 PointeeTy = IntTy;
2666 }
2667 }
2668}
2669
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002670void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002671 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002672 // We follow the behavior of gcc, expanding structures which are
2673 // directly pointed to, and expanding embedded structures. Note that
2674 // these rules are sufficient to prevent recursive encoding of the
2675 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002676 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2677 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002678}
2679
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002680static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002681 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002682 const Expr *E = FD->getBitWidth();
2683 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2684 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002685 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002686 S += 'b';
2687 S += llvm::utostr(N);
2688}
2689
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002690void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2691 bool ExpandPointedToStructures,
2692 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002693 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002694 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002695 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002696 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002697 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002698 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002699 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002700 else {
2701 char encoding;
2702 switch (BT->getKind()) {
2703 default: assert(0 && "Unhandled builtin type kind");
2704 case BuiltinType::Void: encoding = 'v'; break;
2705 case BuiltinType::Bool: encoding = 'B'; break;
2706 case BuiltinType::Char_U:
2707 case BuiltinType::UChar: encoding = 'C'; break;
2708 case BuiltinType::UShort: encoding = 'S'; break;
2709 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002710 case BuiltinType::ULong:
2711 encoding =
2712 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2713 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002714 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002715 case BuiltinType::ULongLong: encoding = 'Q'; break;
2716 case BuiltinType::Char_S:
2717 case BuiltinType::SChar: encoding = 'c'; break;
2718 case BuiltinType::Short: encoding = 's'; break;
2719 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002720 case BuiltinType::Long:
2721 encoding =
2722 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2723 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002724 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002725 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002726 case BuiltinType::Float: encoding = 'f'; break;
2727 case BuiltinType::Double: encoding = 'd'; break;
2728 case BuiltinType::LongDouble: encoding = 'd'; break;
2729 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002730
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002731 S += encoding;
2732 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002733 } else if (const ComplexType *CT = T->getAsComplexType()) {
2734 S += 'j';
2735 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2736 false);
2737 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002738 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2739 ExpandPointedToStructures,
2740 ExpandStructures, FD);
2741 if (FD || EncodingProperty) {
2742 // Note that we do extended encoding of protocol qualifer list
2743 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002744 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002745 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002746 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002747 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002748 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002749 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002750 S += '>';
2751 }
2752 S += '"';
2753 }
2754 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002755 }
2756 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002757 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002758 bool isReadOnly = false;
2759 // For historical/compatibility reasons, the read-only qualifier of the
2760 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2761 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2762 // Also, do not emit the 'r' for anything but the outermost type!
2763 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2764 if (OutermostType && T.isConstQualified()) {
2765 isReadOnly = true;
2766 S += 'r';
2767 }
2768 }
2769 else if (OutermostType) {
2770 QualType P = PointeeTy;
2771 while (P->getAsPointerType())
2772 P = P->getAsPointerType()->getPointeeType();
2773 if (P.isConstQualified()) {
2774 isReadOnly = true;
2775 S += 'r';
2776 }
2777 }
2778 if (isReadOnly) {
2779 // Another legacy compatibility encoding. Some ObjC qualifier and type
2780 // combinations need to be rearranged.
2781 // Rewrite "in const" from "nr" to "rn"
2782 const char * s = S.c_str();
2783 int len = S.length();
2784 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2785 std::string replace = "rn";
2786 S.replace(S.end()-2, S.end(), replace);
2787 }
2788 }
Steve Naroff389bf462009-02-12 17:52:19 +00002789 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002790 S += '@';
2791 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002792 }
2793 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002794 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002795 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002796 // Another historical/compatibility reason.
2797 // We encode the underlying type which comes out as
2798 // {...};
2799 S += '^';
2800 getObjCEncodingForTypeImpl(PointeeTy, S,
2801 false, ExpandPointedToStructures,
2802 NULL);
2803 return;
2804 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002805 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002806 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002807 const ObjCInterfaceType *OIT =
2808 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002809 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002810 S += '"';
2811 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002812 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2813 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002814 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002815 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002816 S += '>';
2817 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002818 S += '"';
2819 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002820 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002821 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002822 S += '#';
2823 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002824 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002825 S += ':';
2826 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002827 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002828
2829 if (PointeeTy->isCharType()) {
2830 // char pointer types should be encoded as '*' unless it is a
2831 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002832 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002833 S += '*';
2834 return;
2835 }
2836 }
2837
2838 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002839 getLegacyIntegralTypeEncoding(PointeeTy);
2840
2841 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002842 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002843 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002844 } else if (const ArrayType *AT =
2845 // Ignore type qualifiers etc.
2846 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002847 if (isa<IncompleteArrayType>(AT)) {
2848 // Incomplete arrays are encoded as a pointer to the array element.
2849 S += '^';
2850
2851 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2852 false, ExpandStructures, FD);
2853 } else {
2854 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002855
Anders Carlsson559a8332009-02-22 01:38:57 +00002856 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2857 S += llvm::utostr(CAT->getSize().getZExtValue());
2858 else {
2859 //Variable length arrays are encoded as a regular array with 0 elements.
2860 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2861 S += '0';
2862 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002863
Anders Carlsson559a8332009-02-22 01:38:57 +00002864 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2865 false, ExpandStructures, FD);
2866 S += ']';
2867 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002868 } else if (T->getAsFunctionType()) {
2869 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002870 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002871 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002872 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002873 // Anonymous structures print as '?'
2874 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2875 S += II->getName();
2876 } else {
2877 S += '?';
2878 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002879 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002880 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002881 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2882 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002883 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002884 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002885 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002886 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002887 S += '"';
2888 }
2889
2890 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002891 if (Field->isBitField()) {
2892 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2893 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002894 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002895 QualType qt = Field->getType();
2896 getLegacyIntegralTypeEncoding(qt);
2897 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002898 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002899 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002900 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002901 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002902 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002903 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002904 if (FD && FD->isBitField())
2905 EncodeBitField(this, S, FD);
2906 else
2907 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002908 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002909 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002910 } else if (T->isObjCInterfaceType()) {
2911 // @encode(class_name)
2912 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2913 S += '{';
2914 const IdentifierInfo *II = OI->getIdentifier();
2915 S += II->getName();
2916 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002917 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002918 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002919 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002920 if (RecFields[i]->isBitField())
2921 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2922 RecFields[i]);
2923 else
2924 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2925 FD);
2926 }
2927 S += '}';
2928 }
2929 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002930 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002931}
2932
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002933void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002934 std::string& S) const {
2935 if (QT & Decl::OBJC_TQ_In)
2936 S += 'n';
2937 if (QT & Decl::OBJC_TQ_Inout)
2938 S += 'N';
2939 if (QT & Decl::OBJC_TQ_Out)
2940 S += 'o';
2941 if (QT & Decl::OBJC_TQ_Bycopy)
2942 S += 'O';
2943 if (QT & Decl::OBJC_TQ_Byref)
2944 S += 'R';
2945 if (QT & Decl::OBJC_TQ_Oneway)
2946 S += 'V';
2947}
2948
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002949void ASTContext::setBuiltinVaListType(QualType T)
2950{
2951 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2952
2953 BuiltinVaListType = T;
2954}
2955
Douglas Gregor319ac892009-04-23 22:29:11 +00002956void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002957{
Douglas Gregor319ac892009-04-23 22:29:11 +00002958 ObjCIdType = T;
2959
2960 const TypedefType *TT = T->getAsTypedefType();
2961 if (!TT)
2962 return;
2963
2964 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002965
2966 // typedef struct objc_object *id;
2967 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002968 // User error - caller will issue diagnostics.
2969 if (!ptr)
2970 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002971 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002972 // User error - caller will issue diagnostics.
2973 if (!rec)
2974 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002975 IdStructType = rec;
2976}
2977
Douglas Gregor319ac892009-04-23 22:29:11 +00002978void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002979{
Douglas Gregor319ac892009-04-23 22:29:11 +00002980 ObjCSelType = T;
2981
2982 const TypedefType *TT = T->getAsTypedefType();
2983 if (!TT)
2984 return;
2985 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002986
2987 // typedef struct objc_selector *SEL;
2988 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002989 if (!ptr)
2990 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002991 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002992 if (!rec)
2993 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002994 SelStructType = rec;
2995}
2996
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002997void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002998{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003000}
3001
Douglas Gregor319ac892009-04-23 22:29:11 +00003002void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00003003{
Douglas Gregor319ac892009-04-23 22:29:11 +00003004 ObjCClassType = T;
3005
3006 const TypedefType *TT = T->getAsTypedefType();
3007 if (!TT)
3008 return;
3009 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00003010
3011 // typedef struct objc_class *Class;
3012 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
3013 assert(ptr && "'Class' incorrectly typed");
3014 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
3015 assert(rec && "'Class' incorrectly typed");
3016 ClassStructType = rec;
3017}
3018
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003019void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3020 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003021 "'NSConstantString' type already set!");
3022
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003023 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003024}
3025
Douglas Gregor7532dc62009-03-30 22:58:21 +00003026/// \brief Retrieve the template name that represents a qualified
3027/// template name such as \c std::vector.
3028TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3029 bool TemplateKeyword,
3030 TemplateDecl *Template) {
3031 llvm::FoldingSetNodeID ID;
3032 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3033
3034 void *InsertPos = 0;
3035 QualifiedTemplateName *QTN =
3036 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3037 if (!QTN) {
3038 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3039 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3040 }
3041
3042 return TemplateName(QTN);
3043}
3044
3045/// \brief Retrieve the template name that represents a dependent
3046/// template name such as \c MetaFun::template apply.
3047TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3048 const IdentifierInfo *Name) {
3049 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3050
3051 llvm::FoldingSetNodeID ID;
3052 DependentTemplateName::Profile(ID, NNS, Name);
3053
3054 void *InsertPos = 0;
3055 DependentTemplateName *QTN =
3056 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3057
3058 if (QTN)
3059 return TemplateName(QTN);
3060
3061 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3062 if (CanonNNS == NNS) {
3063 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3064 } else {
3065 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3066 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3067 }
3068
3069 DependentTemplateNames.InsertNode(QTN, InsertPos);
3070 return TemplateName(QTN);
3071}
3072
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003073/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003074/// TargetInfo, produce the corresponding type. The unsigned @p Type
3075/// is actually a value of type @c TargetInfo::IntType.
3076QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003077 switch (Type) {
3078 case TargetInfo::NoInt: return QualType();
3079 case TargetInfo::SignedShort: return ShortTy;
3080 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3081 case TargetInfo::SignedInt: return IntTy;
3082 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3083 case TargetInfo::SignedLong: return LongTy;
3084 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3085 case TargetInfo::SignedLongLong: return LongLongTy;
3086 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3087 }
3088
3089 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003090 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003091}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003092
3093//===----------------------------------------------------------------------===//
3094// Type Predicates.
3095//===----------------------------------------------------------------------===//
3096
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003097/// isObjCNSObjectType - Return true if this is an NSObject object using
3098/// NSObject attribute on a c-style pointer type.
3099/// FIXME - Make it work directly on types.
3100///
3101bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3102 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3103 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003104 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003105 return true;
3106 }
3107 return false;
3108}
3109
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003110/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3111/// to an object type. This includes "id" and "Class" (two 'special' pointers
3112/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3113/// ID type).
3114bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00003115 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003116 return true;
3117
Steve Naroff6ae98502008-10-21 18:24:04 +00003118 // Blocks are objects.
3119 if (Ty->isBlockPointerType())
3120 return true;
3121
3122 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00003123 const PointerType *PT = Ty->getAsPointerType();
3124 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003125 return false;
3126
Chris Lattner16ede0e2009-04-12 23:51:02 +00003127 // If this a pointer to an interface (e.g. NSString*), it is ok.
3128 if (PT->getPointeeType()->isObjCInterfaceType() ||
3129 // If is has NSObject attribute, OK as well.
3130 isObjCNSObjectType(Ty))
3131 return true;
3132
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003133 // Check to see if this is 'id' or 'Class', both of which are typedefs for
3134 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00003135 // underlying type. Iteratively strip off typedefs so that we can handle
3136 // typedefs of typedefs.
3137 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3138 if (Ty.getUnqualifiedType() == getObjCIdType() ||
3139 Ty.getUnqualifiedType() == getObjCClassType())
3140 return true;
3141
3142 Ty = TDT->getDecl()->getUnderlyingType();
3143 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003144
Chris Lattner16ede0e2009-04-12 23:51:02 +00003145 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003146}
3147
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003148/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3149/// garbage collection attribute.
3150///
3151QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003152 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003153 if (getLangOptions().ObjC1 &&
3154 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003155 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003156 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003157 // (or pointers to them) be treated as though they were declared
3158 // as __strong.
3159 if (GCAttrs == QualType::GCNone) {
3160 if (isObjCObjectPointerType(Ty))
3161 GCAttrs = QualType::Strong;
3162 else if (Ty->isPointerType())
3163 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3164 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003165 // Non-pointers have none gc'able attribute regardless of the attribute
3166 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003167 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003168 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003169 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003170 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003171}
3172
Chris Lattner6ac46a42008-04-07 06:51:04 +00003173//===----------------------------------------------------------------------===//
3174// Type Compatibility Testing
3175//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003176
Chris Lattner6ac46a42008-04-07 06:51:04 +00003177/// areCompatVectorTypes - Return true if the two specified vector types are
3178/// compatible.
3179static bool areCompatVectorTypes(const VectorType *LHS,
3180 const VectorType *RHS) {
3181 assert(LHS->isCanonical() && RHS->isCanonical());
3182 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003183 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003184}
3185
Eli Friedman3d815e72008-08-22 00:56:42 +00003186/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003187/// compatible for assignment from RHS to LHS. This handles validation of any
3188/// protocol qualifiers on the LHS or RHS.
3189///
Eli Friedman3d815e72008-08-22 00:56:42 +00003190bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3191 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003192 // Verify that the base decls are compatible: the RHS must be a subclass of
3193 // the LHS.
3194 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3195 return false;
3196
3197 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3198 // protocol qualified at all, then we are good.
3199 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3200 return true;
3201
3202 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3203 // isn't a superset.
3204 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3205 return true; // FIXME: should return false!
3206
3207 // Finally, we must have two protocol-qualified interfaces.
3208 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3209 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003210
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003211 // All LHS protocols must have a presence on the RHS.
3212 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003213
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003214 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3215 LHSPE = LHSP->qual_end();
3216 LHSPI != LHSPE; LHSPI++) {
3217 bool RHSImplementsProtocol = false;
3218
3219 // If the RHS doesn't implement the protocol on the left, the types
3220 // are incompatible.
3221 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3222 RHSPE = RHSP->qual_end();
3223 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3224 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3225 RHSImplementsProtocol = true;
3226 }
3227 // FIXME: For better diagnostics, consider passing back the protocol name.
3228 if (!RHSImplementsProtocol)
3229 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003230 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003231 // The RHS implements all protocols listed on the LHS.
3232 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003233}
3234
Steve Naroff389bf462009-02-12 17:52:19 +00003235bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3236 // get the "pointed to" types
3237 const PointerType *LHSPT = LHS->getAsPointerType();
3238 const PointerType *RHSPT = RHS->getAsPointerType();
3239
3240 if (!LHSPT || !RHSPT)
3241 return false;
3242
3243 QualType lhptee = LHSPT->getPointeeType();
3244 QualType rhptee = RHSPT->getPointeeType();
3245 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
3246 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
3247 // ID acts sort of like void* for ObjC interfaces
3248 if (LHSIface && isObjCIdStructType(rhptee))
3249 return true;
3250 if (RHSIface && isObjCIdStructType(lhptee))
3251 return true;
3252 if (!LHSIface || !RHSIface)
3253 return false;
3254 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
3255 canAssignObjCInterfaces(RHSIface, LHSIface);
3256}
3257
Steve Naroffec0550f2007-10-15 20:41:53 +00003258/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3259/// both shall have the identically qualified version of a compatible type.
3260/// C99 6.2.7p1: Two types have compatible types if their types are the
3261/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003262bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3263 return !mergeTypes(LHS, RHS).isNull();
3264}
3265
3266QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3267 const FunctionType *lbase = lhs->getAsFunctionType();
3268 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003269 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3270 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003271 bool allLTypes = true;
3272 bool allRTypes = true;
3273
3274 // Check return type
3275 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3276 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003277 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3278 allLTypes = false;
3279 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3280 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003281
3282 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003283 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3284 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003285 unsigned lproto_nargs = lproto->getNumArgs();
3286 unsigned rproto_nargs = rproto->getNumArgs();
3287
3288 // Compatible functions must have the same number of arguments
3289 if (lproto_nargs != rproto_nargs)
3290 return QualType();
3291
3292 // Variadic and non-variadic functions aren't compatible
3293 if (lproto->isVariadic() != rproto->isVariadic())
3294 return QualType();
3295
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003296 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3297 return QualType();
3298
Eli Friedman3d815e72008-08-22 00:56:42 +00003299 // Check argument compatibility
3300 llvm::SmallVector<QualType, 10> types;
3301 for (unsigned i = 0; i < lproto_nargs; i++) {
3302 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3303 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3304 QualType argtype = mergeTypes(largtype, rargtype);
3305 if (argtype.isNull()) return QualType();
3306 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003307 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3308 allLTypes = false;
3309 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3310 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003311 }
3312 if (allLTypes) return lhs;
3313 if (allRTypes) return rhs;
3314 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003315 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003316 }
3317
3318 if (lproto) allRTypes = false;
3319 if (rproto) allLTypes = false;
3320
Douglas Gregor72564e72009-02-26 23:50:07 +00003321 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003322 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003323 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003324 if (proto->isVariadic()) return QualType();
3325 // Check that the types are compatible with the types that
3326 // would result from default argument promotions (C99 6.7.5.3p15).
3327 // The only types actually affected are promotable integer
3328 // types and floats, which would be passed as a different
3329 // type depending on whether the prototype is visible.
3330 unsigned proto_nargs = proto->getNumArgs();
3331 for (unsigned i = 0; i < proto_nargs; ++i) {
3332 QualType argTy = proto->getArgType(i);
3333 if (argTy->isPromotableIntegerType() ||
3334 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3335 return QualType();
3336 }
3337
3338 if (allLTypes) return lhs;
3339 if (allRTypes) return rhs;
3340 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003341 proto->getNumArgs(), lproto->isVariadic(),
3342 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003343 }
3344
3345 if (allLTypes) return lhs;
3346 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003347 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003348}
3349
3350QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003351 // C++ [expr]: If an expression initially has the type "reference to T", the
3352 // type is adjusted to "T" prior to any further analysis, the expression
3353 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003354 // expression is an lvalue unless the reference is an rvalue reference and
3355 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003356 // FIXME: C++ shouldn't be going through here! The rules are different
3357 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003358 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3359 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003360 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003361 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003362 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003363 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003364
Eli Friedman3d815e72008-08-22 00:56:42 +00003365 QualType LHSCan = getCanonicalType(LHS),
3366 RHSCan = getCanonicalType(RHS);
3367
3368 // If two types are identical, they are compatible.
3369 if (LHSCan == RHSCan)
3370 return LHS;
3371
3372 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003373 // Note that we handle extended qualifiers later, in the
3374 // case for ExtQualType.
3375 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003376 return QualType();
3377
Eli Friedman852d63b2009-06-01 01:22:52 +00003378 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3379 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003380
Chris Lattner1adb8832008-01-14 05:45:46 +00003381 // We want to consider the two function types to be the same for these
3382 // comparisons, just force one to the other.
3383 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3384 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003385
Eli Friedman07d25872009-06-02 05:28:56 +00003386 // Strip off objc_gc attributes off the top level so they can be merged.
3387 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003388 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003389 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3390 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003391 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003392 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003393 // __strong attribue is redundant if other decl is an objective-c
3394 // object pointer (or decorated with __strong attribute); otherwise
3395 // issue error.
3396 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3397 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3398 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3399 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003400 return QualType();
3401
Eli Friedman07d25872009-06-02 05:28:56 +00003402 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3403 RHS.getCVRQualifiers());
3404 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003405 if (!Result.isNull()) {
3406 if (Result.getObjCGCAttr() == QualType::GCNone)
3407 Result = getObjCGCQualType(Result, GCAttr);
3408 else if (Result.getObjCGCAttr() != GCAttr)
3409 Result = QualType();
3410 }
Eli Friedman07d25872009-06-02 05:28:56 +00003411 return Result;
3412 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003413 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003414 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003415 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3416 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003417 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3418 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003419 // __strong attribue is redundant if other decl is an objective-c
3420 // object pointer (or decorated with __strong attribute); otherwise
3421 // issue error.
3422 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3423 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3424 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3425 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003426 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003427
Eli Friedman07d25872009-06-02 05:28:56 +00003428 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3429 LHS.getCVRQualifiers());
3430 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003431 if (!Result.isNull()) {
3432 if (Result.getObjCGCAttr() == QualType::GCNone)
3433 Result = getObjCGCQualType(Result, GCAttr);
3434 else if (Result.getObjCGCAttr() != GCAttr)
3435 Result = QualType();
3436 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003437 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003438 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003439 }
3440
Eli Friedman4c721d32008-02-12 08:23:06 +00003441 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003442 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3443 LHSClass = Type::ConstantArray;
3444 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3445 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003446
Nate Begeman213541a2008-04-18 23:10:10 +00003447 // Canonicalize ExtVector -> Vector.
3448 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3449 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003450
Chris Lattnerb0489812008-04-07 06:38:24 +00003451 // Consider qualified interfaces and interfaces the same.
3452 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3453 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003454
Chris Lattnera36a61f2008-04-07 05:43:21 +00003455 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003456 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003457 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3458 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003459
Steve Naroffd824c9c2009-04-14 15:11:46 +00003460 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3461 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003462 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003463 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003464 return RHS;
3465
Steve Naroffbc76dd02008-12-10 22:14:21 +00003466 // ID is compatible with all qualified id types.
3467 if (LHS->isObjCQualifiedIdType()) {
3468 if (const PointerType *PT = RHS->getAsPointerType()) {
3469 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003470 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003471 return LHS;
3472 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3473 // Unfortunately, this API is part of Sema (which we don't have access
3474 // to. Need to refactor. The following check is insufficient, since we
3475 // need to make sure the class implements the protocol.
3476 if (pType->isObjCInterfaceType())
3477 return LHS;
3478 }
3479 }
3480 if (RHS->isObjCQualifiedIdType()) {
3481 if (const PointerType *PT = LHS->getAsPointerType()) {
3482 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003483 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003484 return RHS;
3485 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3486 // Unfortunately, this API is part of Sema (which we don't have access
3487 // to. Need to refactor. The following check is insufficient, since we
3488 // need to make sure the class implements the protocol.
3489 if (pType->isObjCInterfaceType())
3490 return RHS;
3491 }
3492 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003493 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3494 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003495 if (const EnumType* ETy = LHS->getAsEnumType()) {
3496 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3497 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003498 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003499 if (const EnumType* ETy = RHS->getAsEnumType()) {
3500 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3501 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003502 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003503
Eli Friedman3d815e72008-08-22 00:56:42 +00003504 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003505 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003506
Steve Naroff4a746782008-01-09 22:43:08 +00003507 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003508 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003509#define TYPE(Class, Base)
3510#define ABSTRACT_TYPE(Class, Base)
3511#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3512#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3513#include "clang/AST/TypeNodes.def"
3514 assert(false && "Non-canonical and dependent types shouldn't get here");
3515 return QualType();
3516
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003517 case Type::LValueReference:
3518 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003519 case Type::MemberPointer:
3520 assert(false && "C++ should never be in mergeTypes");
3521 return QualType();
3522
3523 case Type::IncompleteArray:
3524 case Type::VariableArray:
3525 case Type::FunctionProto:
3526 case Type::ExtVector:
3527 case Type::ObjCQualifiedInterface:
3528 assert(false && "Types are eliminated above");
3529 return QualType();
3530
Chris Lattner1adb8832008-01-14 05:45:46 +00003531 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003532 {
3533 // Merge two pointer types, while trying to preserve typedef info
3534 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3535 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3536 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3537 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003538 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003539 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003540 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003541 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003542 return getPointerType(ResultType);
3543 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003544 case Type::BlockPointer:
3545 {
3546 // Merge two block pointer types, while trying to preserve typedef info
3547 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3548 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3549 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3550 if (ResultType.isNull()) return QualType();
3551 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3552 return LHS;
3553 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3554 return RHS;
3555 return getBlockPointerType(ResultType);
3556 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003557 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003558 {
3559 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3560 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3561 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3562 return QualType();
3563
3564 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3565 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3566 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3567 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003568 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3569 return LHS;
3570 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3571 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003572 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3573 ArrayType::ArraySizeModifier(), 0);
3574 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3575 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003576 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3577 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003578 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3579 return LHS;
3580 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3581 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003582 if (LVAT) {
3583 // FIXME: This isn't correct! But tricky to implement because
3584 // the array's size has to be the size of LHS, but the type
3585 // has to be different.
3586 return LHS;
3587 }
3588 if (RVAT) {
3589 // FIXME: This isn't correct! But tricky to implement because
3590 // the array's size has to be the size of RHS, but the type
3591 // has to be different.
3592 return RHS;
3593 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003594 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3595 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003596 return getIncompleteArrayType(ResultType,
3597 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003598 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003599 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003600 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003601 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003602 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003603 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003604 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3605 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003606 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003607 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003608 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003609 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003610 case Type::Complex:
3611 // Distinct complex types are incompatible.
3612 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003613 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003614 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003615 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3616 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003617 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003618 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003619 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003620 // FIXME: This should be type compatibility, e.g. whether
3621 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003622 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3623 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3624 if (LHSIface && RHSIface &&
3625 canAssignObjCInterfaces(LHSIface, RHSIface))
3626 return LHS;
3627
Eli Friedman3d815e72008-08-22 00:56:42 +00003628 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003629 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003630 case Type::ObjCObjectPointer:
3631 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003632 // Distinct qualified id's are not compatible.
3633 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003634 case Type::FixedWidthInt:
3635 // Distinct fixed-width integers are not compatible.
3636 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003637 case Type::ExtQual:
3638 // FIXME: ExtQual types can be compatible even if they're not
3639 // identical!
3640 return QualType();
3641 // First attempt at an implementation, but I'm not really sure it's
3642 // right...
3643#if 0
3644 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3645 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3646 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3647 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3648 return QualType();
3649 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3650 LHSBase = QualType(LQual->getBaseType(), 0);
3651 RHSBase = QualType(RQual->getBaseType(), 0);
3652 ResultType = mergeTypes(LHSBase, RHSBase);
3653 if (ResultType.isNull()) return QualType();
3654 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3655 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3656 return LHS;
3657 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3658 return RHS;
3659 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3660 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3661 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3662 return ResultType;
3663#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003664
3665 case Type::TemplateSpecialization:
3666 assert(false && "Dependent types have no size");
3667 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003668 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003669
3670 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003671}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003672
Chris Lattner5426bf62008-04-07 07:01:58 +00003673//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003674// Integer Predicates
3675//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003676
Eli Friedmanad74a752008-06-28 06:23:08 +00003677unsigned ASTContext::getIntWidth(QualType T) {
3678 if (T == BoolTy)
3679 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003680 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3681 return FWIT->getWidth();
3682 }
3683 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003684 return (unsigned)getTypeSize(T);
3685}
3686
3687QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3688 assert(T->isSignedIntegerType() && "Unexpected type");
3689 if (const EnumType* ETy = T->getAsEnumType())
3690 T = ETy->getDecl()->getIntegerType();
3691 const BuiltinType* BTy = T->getAsBuiltinType();
3692 assert (BTy && "Unexpected signed integer type");
3693 switch (BTy->getKind()) {
3694 case BuiltinType::Char_S:
3695 case BuiltinType::SChar:
3696 return UnsignedCharTy;
3697 case BuiltinType::Short:
3698 return UnsignedShortTy;
3699 case BuiltinType::Int:
3700 return UnsignedIntTy;
3701 case BuiltinType::Long:
3702 return UnsignedLongTy;
3703 case BuiltinType::LongLong:
3704 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003705 case BuiltinType::Int128:
3706 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003707 default:
3708 assert(0 && "Unexpected signed integer type");
3709 return QualType();
3710 }
3711}
3712
Douglas Gregor2cf26342009-04-09 22:27:44 +00003713ExternalASTSource::~ExternalASTSource() { }
3714
3715void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003716
3717
3718//===----------------------------------------------------------------------===//
3719// Builtin Type Computation
3720//===----------------------------------------------------------------------===//
3721
3722/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3723/// pointer over the consumed characters. This returns the resultant type.
3724static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3725 ASTContext::GetBuiltinTypeError &Error,
3726 bool AllowTypeModifiers = true) {
3727 // Modifiers.
3728 int HowLong = 0;
3729 bool Signed = false, Unsigned = false;
3730
3731 // Read the modifiers first.
3732 bool Done = false;
3733 while (!Done) {
3734 switch (*Str++) {
3735 default: Done = true; --Str; break;
3736 case 'S':
3737 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3738 assert(!Signed && "Can't use 'S' modifier multiple times!");
3739 Signed = true;
3740 break;
3741 case 'U':
3742 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3743 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3744 Unsigned = true;
3745 break;
3746 case 'L':
3747 assert(HowLong <= 2 && "Can't have LLLL modifier");
3748 ++HowLong;
3749 break;
3750 }
3751 }
3752
3753 QualType Type;
3754
3755 // Read the base type.
3756 switch (*Str++) {
3757 default: assert(0 && "Unknown builtin type letter!");
3758 case 'v':
3759 assert(HowLong == 0 && !Signed && !Unsigned &&
3760 "Bad modifiers used with 'v'!");
3761 Type = Context.VoidTy;
3762 break;
3763 case 'f':
3764 assert(HowLong == 0 && !Signed && !Unsigned &&
3765 "Bad modifiers used with 'f'!");
3766 Type = Context.FloatTy;
3767 break;
3768 case 'd':
3769 assert(HowLong < 2 && !Signed && !Unsigned &&
3770 "Bad modifiers used with 'd'!");
3771 if (HowLong)
3772 Type = Context.LongDoubleTy;
3773 else
3774 Type = Context.DoubleTy;
3775 break;
3776 case 's':
3777 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3778 if (Unsigned)
3779 Type = Context.UnsignedShortTy;
3780 else
3781 Type = Context.ShortTy;
3782 break;
3783 case 'i':
3784 if (HowLong == 3)
3785 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3786 else if (HowLong == 2)
3787 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3788 else if (HowLong == 1)
3789 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3790 else
3791 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3792 break;
3793 case 'c':
3794 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3795 if (Signed)
3796 Type = Context.SignedCharTy;
3797 else if (Unsigned)
3798 Type = Context.UnsignedCharTy;
3799 else
3800 Type = Context.CharTy;
3801 break;
3802 case 'b': // boolean
3803 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3804 Type = Context.BoolTy;
3805 break;
3806 case 'z': // size_t.
3807 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3808 Type = Context.getSizeType();
3809 break;
3810 case 'F':
3811 Type = Context.getCFConstantStringType();
3812 break;
3813 case 'a':
3814 Type = Context.getBuiltinVaListType();
3815 assert(!Type.isNull() && "builtin va list type not initialized!");
3816 break;
3817 case 'A':
3818 // This is a "reference" to a va_list; however, what exactly
3819 // this means depends on how va_list is defined. There are two
3820 // different kinds of va_list: ones passed by value, and ones
3821 // passed by reference. An example of a by-value va_list is
3822 // x86, where va_list is a char*. An example of by-ref va_list
3823 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3824 // we want this argument to be a char*&; for x86-64, we want
3825 // it to be a __va_list_tag*.
3826 Type = Context.getBuiltinVaListType();
3827 assert(!Type.isNull() && "builtin va list type not initialized!");
3828 if (Type->isArrayType()) {
3829 Type = Context.getArrayDecayedType(Type);
3830 } else {
3831 Type = Context.getLValueReferenceType(Type);
3832 }
3833 break;
3834 case 'V': {
3835 char *End;
3836
3837 unsigned NumElements = strtoul(Str, &End, 10);
3838 assert(End != Str && "Missing vector size");
3839
3840 Str = End;
3841
3842 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3843 Type = Context.getVectorType(ElementType, NumElements);
3844 break;
3845 }
3846 case 'P': {
3847 IdentifierInfo *II = &Context.Idents.get("FILE");
3848 DeclContext::lookup_result Lookup
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003849 = Context.getTranslationUnitDecl()->lookup(II);
Chris Lattner86df27b2009-06-14 00:45:47 +00003850 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3851 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3852 break;
3853 }
3854 else {
3855 Error = ASTContext::GE_Missing_FILE;
3856 return QualType();
3857 }
3858 }
3859 }
3860
3861 if (!AllowTypeModifiers)
3862 return Type;
3863
3864 Done = false;
3865 while (!Done) {
3866 switch (*Str++) {
3867 default: Done = true; --Str; break;
3868 case '*':
3869 Type = Context.getPointerType(Type);
3870 break;
3871 case '&':
3872 Type = Context.getLValueReferenceType(Type);
3873 break;
3874 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3875 case 'C':
3876 Type = Type.getQualifiedType(QualType::Const);
3877 break;
3878 }
3879 }
3880
3881 return Type;
3882}
3883
3884/// GetBuiltinType - Return the type for the specified builtin.
3885QualType ASTContext::GetBuiltinType(unsigned id,
3886 GetBuiltinTypeError &Error) {
3887 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3888
3889 llvm::SmallVector<QualType, 8> ArgTypes;
3890
3891 Error = GE_None;
3892 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3893 if (Error != GE_None)
3894 return QualType();
3895 while (TypeStr[0] && TypeStr[0] != '.') {
3896 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3897 if (Error != GE_None)
3898 return QualType();
3899
3900 // Do array -> pointer decay. The builtin should use the decayed type.
3901 if (Ty->isArrayType())
3902 Ty = getArrayDecayedType(Ty);
3903
3904 ArgTypes.push_back(Ty);
3905 }
3906
3907 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3908 "'.' should only occur at end of builtin type list!");
3909
3910 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3911 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3912 return getFunctionNoProtoType(ResType);
3913 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3914 TypeStr[0] == '.', 0);
3915}