blob: 0075815300c3a9943fc3ed0e494e00fc8d40b619 [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
Steve Narofffb22d962007-08-30 01:06:46 +0000478 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000479 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000480
Chris Lattner98be4942008-03-05 18:54:05 +0000481 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000482 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000483 Align = EltInfo.second;
484 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000485 }
Nate Begeman213541a2008-04-18 23:10:10 +0000486 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000487 case Type::Vector: {
488 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000489 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000490 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000491 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000492 // If the alignment is not a power of 2, round up to the next power of 2.
493 // This happens for non-power-of-2 length vectors.
494 // FIXME: this should probably be a target property.
495 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000496 break;
497 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000498
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000499 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000500 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000501 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000502 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000503 // GCC extension: alignof(void) = 8 bits.
504 Width = 0;
505 Align = 8;
506 break;
507
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000508 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000509 Width = Target.getBoolWidth();
510 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000511 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000512 case BuiltinType::Char_S:
513 case BuiltinType::Char_U:
514 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000515 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000516 Width = Target.getCharWidth();
517 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000518 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000519 case BuiltinType::WChar:
520 Width = Target.getWCharWidth();
521 Align = Target.getWCharAlign();
522 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000523 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000524 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000525 Width = Target.getShortWidth();
526 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000527 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000528 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000529 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000530 Width = Target.getIntWidth();
531 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000532 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000533 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000534 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000535 Width = Target.getLongWidth();
536 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000537 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000538 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000539 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000540 Width = Target.getLongLongWidth();
541 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000542 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000543 case BuiltinType::Int128:
544 case BuiltinType::UInt128:
545 Width = 128;
546 Align = 128; // int128_t is 128-bit aligned on all targets.
547 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000548 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000549 Width = Target.getFloatWidth();
550 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000551 break;
552 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000553 Width = Target.getDoubleWidth();
554 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000555 break;
556 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000557 Width = Target.getLongDoubleWidth();
558 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000560 case BuiltinType::NullPtr:
561 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
562 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000563 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000564 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000565 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000566 case Type::FixedWidthInt:
567 // FIXME: This isn't precisely correct; the width/alignment should depend
568 // on the available types for the target
569 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000570 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000571 Align = Width;
572 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000573 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000574 // FIXME: Pointers into different addr spaces could have different sizes and
575 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000576 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000577 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000578 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000579 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000580 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000581 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000582 case Type::BlockPointer: {
583 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
584 Width = Target.getPointerWidth(AS);
585 Align = Target.getPointerAlign(AS);
586 break;
587 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000588 case Type::Pointer: {
589 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000590 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000591 Align = Target.getPointerAlign(AS);
592 break;
593 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000594 case Type::LValueReference:
595 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000596 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000597 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000598 // FIXME: This is wrong for struct layout: a reference in a struct has
599 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000600 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000601 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000602 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
603 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
604 // If we ever want to support other ABIs this needs to be abstracted.
605
Sebastian Redlf30208a2009-01-24 21:16:55 +0000606 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000607 std::pair<uint64_t, unsigned> PtrDiffInfo =
608 getTypeInfo(getPointerDiffType());
609 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000610 if (Pointee->isFunctionType())
611 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000612 Align = PtrDiffInfo.second;
613 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000614 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000615 case Type::Complex: {
616 // Complex types have the same alignment as their elements, but twice the
617 // size.
618 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000619 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000620 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000621 Align = EltInfo.second;
622 break;
623 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000624 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000625 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000626 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
627 Width = Layout.getSize();
628 Align = Layout.getAlignment();
629 break;
630 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000631 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000632 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000633 const TagType *TT = cast<TagType>(T);
634
635 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000636 Width = 1;
637 Align = 1;
638 break;
639 }
640
Daniel Dunbar1d751182008-11-08 05:48:37 +0000641 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000642 return getTypeInfo(ET->getDecl()->getIntegerType());
643
Daniel Dunbar1d751182008-11-08 05:48:37 +0000644 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000645 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
646 Width = Layout.getSize();
647 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000648 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000649 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000650
Douglas Gregor18857642009-04-30 17:32:17 +0000651 case Type::Typedef: {
652 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000653 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000654 Align = Aligned->getAlignment();
655 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
656 } else
657 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000658 break;
Chris Lattner71763312008-04-06 22:05:18 +0000659 }
Douglas Gregor18857642009-04-30 17:32:17 +0000660
661 case Type::TypeOfExpr:
662 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
663 .getTypePtr());
664
665 case Type::TypeOf:
666 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
667
Anders Carlsson395b4752009-06-24 19:06:50 +0000668 case Type::Decltype:
669 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
670 .getTypePtr());
671
Douglas Gregor18857642009-04-30 17:32:17 +0000672 case Type::QualifiedName:
673 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
674
675 case Type::TemplateSpecialization:
676 assert(getCanonicalType(T) != T &&
677 "Cannot request the size of a dependent type");
678 // FIXME: this is likely to be wrong once we support template
679 // aliases, since a template alias could refer to a typedef that
680 // has an __aligned__ attribute on it.
681 return getTypeInfo(getCanonicalType(T));
682 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000683
Chris Lattner464175b2007-07-18 17:52:12 +0000684 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000685 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000686}
687
Chris Lattner34ebde42009-01-27 18:08:34 +0000688/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
689/// type for the current target in bits. This can be different than the ABI
690/// alignment in cases where it is beneficial for performance to overalign
691/// a data type.
692unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
693 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000694
695 // Double and long long should be naturally aligned if possible.
696 if (const ComplexType* CT = T->getAsComplexType())
697 T = CT->getElementType().getTypePtr();
698 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
699 T->isSpecificBuiltinType(BuiltinType::LongLong))
700 return std::max(ABIAlign, (unsigned)getTypeSize(T));
701
Chris Lattner34ebde42009-01-27 18:08:34 +0000702 return ABIAlign;
703}
704
705
Devang Patel8b277042008-06-04 21:22:16 +0000706/// LayoutField - Field layout.
707void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000708 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000709 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000710 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000711 uint64_t FieldOffset = IsUnion ? 0 : Size;
712 uint64_t FieldSize;
713 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000714
715 // FIXME: Should this override struct packing? Probably we want to
716 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000717 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000718 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000719
720 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
721 // TODO: Need to check this algorithm on other targets!
722 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000723 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000724
725 std::pair<uint64_t, unsigned> FieldInfo =
726 Context.getTypeInfo(FD->getType());
727 uint64_t TypeSize = FieldInfo.first;
728
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000729 // Determine the alignment of this bitfield. The packing
730 // attributes define a maximum and the alignment attribute defines
731 // a minimum.
732 // FIXME: What is the right behavior when the specified alignment
733 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000734 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000735 if (FieldPacking)
736 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000737 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000738 FieldAlign = std::max(FieldAlign, AA->getAlignment());
739
740 // Check if we need to add padding to give the field the correct
741 // alignment.
742 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
743 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
744
745 // Padding members don't affect overall alignment
746 if (!FD->getIdentifier())
747 FieldAlign = 1;
748 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000749 if (FD->getType()->isIncompleteArrayType()) {
750 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000751 // query getTypeInfo about these, so we figure it out here.
752 // Flexible array members don't have any size, but they
753 // have to be aligned appropriately for their element type.
754 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000755 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000756 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000757 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
758 unsigned AS = RT->getPointeeType().getAddressSpace();
759 FieldSize = Context.Target.getPointerWidth(AS);
760 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000761 } else {
762 std::pair<uint64_t, unsigned> FieldInfo =
763 Context.getTypeInfo(FD->getType());
764 FieldSize = FieldInfo.first;
765 FieldAlign = FieldInfo.second;
766 }
767
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000768 // Determine the alignment of this bitfield. The packing
769 // attributes define a maximum and the alignment attribute defines
770 // a minimum. Additionally, the packing alignment must be at least
771 // a byte for non-bitfields.
772 //
773 // FIXME: What is the right behavior when the specified alignment
774 // is smaller than the specified packing?
775 if (FieldPacking)
776 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000777 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000778 FieldAlign = std::max(FieldAlign, AA->getAlignment());
779
780 // Round up the current record size to the field's alignment boundary.
781 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
782 }
783
784 // Place this field at the current location.
785 FieldOffsets[FieldNo] = FieldOffset;
786
787 // Reserve space for this field.
788 if (IsUnion) {
789 Size = std::max(Size, FieldSize);
790 } else {
791 Size = FieldOffset + FieldSize;
792 }
793
Daniel Dunbard6884a02009-05-04 05:16:21 +0000794 // Remember the next available offset.
795 NextOffset = Size;
796
Devang Patel8b277042008-06-04 21:22:16 +0000797 // Remember max struct/class alignment.
798 Alignment = std::max(Alignment, FieldAlign);
799}
800
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000801static void CollectLocalObjCIvars(ASTContext *Ctx,
802 const ObjCInterfaceDecl *OI,
803 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000804 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
805 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000806 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000807 if (!IVDecl->isInvalidDecl())
808 Fields.push_back(cast<FieldDecl>(IVDecl));
809 }
810}
811
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000812void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
813 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
814 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
815 CollectObjCIvars(SuperClass, Fields);
816 CollectLocalObjCIvars(this, OI, Fields);
817}
818
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000819/// ShallowCollectObjCIvars -
820/// Collect all ivars, including those synthesized, in the current class.
821///
822void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
823 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
824 bool CollectSynthesized) {
825 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
826 E = OI->ivar_end(); I != E; ++I) {
827 Ivars.push_back(*I);
828 }
829 if (CollectSynthesized)
830 CollectSynthesizedIvars(OI, Ivars);
831}
832
Fariborz Jahanian98200742009-05-12 18:14:29 +0000833void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
834 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000835 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
836 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000837 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
838 Ivars.push_back(Ivar);
839
840 // Also look into nested protocols.
841 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
842 E = PD->protocol_end(); P != E; ++P)
843 CollectProtocolSynthesizedIvars(*P, Ivars);
844}
845
846/// CollectSynthesizedIvars -
847/// This routine collect synthesized ivars for the designated class.
848///
849void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
850 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000851 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
852 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000853 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
854 Ivars.push_back(Ivar);
855 }
856 // Also look into interface's protocol list for properties declared
857 // in the protocol and whose ivars are synthesized.
858 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
859 PE = OI->protocol_end(); P != PE; ++P) {
860 ObjCProtocolDecl *PD = (*P);
861 CollectProtocolSynthesizedIvars(PD, Ivars);
862 }
863}
864
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000865unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
866 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000867 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
868 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000869 if ((*I)->getPropertyIvarDecl())
870 ++count;
871
872 // Also look into nested protocols.
873 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
874 E = PD->protocol_end(); P != E; ++P)
875 count += CountProtocolSynthesizedIvars(*P);
876 return count;
877}
878
879unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
880{
881 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000882 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
883 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000884 if ((*I)->getPropertyIvarDecl())
885 ++count;
886 }
887 // Also look into interface's protocol list for properties declared
888 // in the protocol and whose ivars are synthesized.
889 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
890 PE = OI->protocol_end(); P != PE; ++P) {
891 ObjCProtocolDecl *PD = (*P);
892 count += CountProtocolSynthesizedIvars(PD);
893 }
894 return count;
895}
896
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000897/// getInterfaceLayoutImpl - Get or compute information about the
898/// layout of the given interface.
899///
900/// \param Impl - If given, also include the layout of the interface's
901/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000902const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000903ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
904 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000905 assert(!D->isForwardDecl() && "Invalid interface decl!");
906
Devang Patel44a3dde2008-06-04 21:54:36 +0000907 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000908 ObjCContainerDecl *Key =
909 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
910 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
911 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000912
Daniel Dunbar453addb2009-05-03 11:16:44 +0000913 unsigned FieldCount = D->ivar_size();
914 // Add in synthesized ivar count if laying out an implementation.
915 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000916 unsigned SynthCount = CountSynthesizedIvars(D);
917 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000918 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000919 // entry. Note we can't cache this because we simply free all
920 // entries later; however we shouldn't look up implementations
921 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000922 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000923 return getObjCLayout(D, 0);
924 }
925
Devang Patel6a5a34c2008-06-06 02:14:01 +0000926 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000927 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000928 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
929 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000930
Daniel Dunbar913af352009-05-07 21:58:26 +0000931 // We start laying out ivars not at the end of the superclass
932 // structure, but at the next byte following the last field.
933 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000934
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000935 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000936 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000937 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000938 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000939 NewEntry->InitializeLayout(FieldCount);
940 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000941
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000942 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000943 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000944 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000945
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000946 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000947 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
948 AA->getAlignment()));
949
950 // Layout each ivar sequentially.
951 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000952 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
953 ShallowCollectObjCIvars(D, Ivars, Impl);
954 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
955 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
956
Devang Patel44a3dde2008-06-04 21:54:36 +0000957 // Finally, round the size of the total struct up to the alignment of the
958 // struct itself.
959 NewEntry->FinalizeLayout();
960 return *NewEntry;
961}
962
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000963const ASTRecordLayout &
964ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
965 return getObjCLayout(D, 0);
966}
967
968const ASTRecordLayout &
969ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
970 return getObjCLayout(D->getClassInterface(), D);
971}
972
Devang Patel88a981b2007-11-01 19:11:01 +0000973/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000974/// specified record (struct/union/class), which indicates its size and field
975/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000976const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000977 D = D->getDefinition(*this);
978 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000979
Chris Lattner464175b2007-07-18 17:52:12 +0000980 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000981 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000982 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000983
Devang Patel88a981b2007-11-01 19:11:01 +0000984 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
985 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
986 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000987 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000988
Douglas Gregore267ff32008-12-11 20:41:00 +0000989 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000990 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000991 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000992
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000993 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000994 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000995 StructPacking = PA->getAlignment();
996
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000997 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000998 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
999 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001000
Eli Friedman4bd998b2008-05-30 09:31:38 +00001001 // Layout each field, for now, just sequentially, respecting alignment. In
1002 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001003 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001004 for (RecordDecl::field_iterator Field = D->field_begin(),
1005 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001006 Field != FieldEnd; (void)++Field, ++FieldIdx)
1007 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001008
1009 // Finally, round the size of the total struct up to the alignment of the
1010 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001011 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001012 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001013}
1014
Chris Lattnera7674d82007-07-13 22:13:22 +00001015//===----------------------------------------------------------------------===//
1016// Type creation/memoization methods
1017//===----------------------------------------------------------------------===//
1018
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001019QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001020 QualType CanT = getCanonicalType(T);
1021 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001022 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001023
1024 // If we are composing extended qualifiers together, merge together into one
1025 // ExtQualType node.
1026 unsigned CVRQuals = T.getCVRQualifiers();
1027 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1028 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001029
Chris Lattnerb7d25532009-02-18 22:53:11 +00001030 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1031 // If this type already has an address space specified, it cannot get
1032 // another one.
1033 assert(EQT->getAddressSpace() == 0 &&
1034 "Type cannot be in multiple addr spaces!");
1035 GCAttr = EQT->getObjCGCAttr();
1036 TypeNode = EQT->getBaseType();
1037 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001038
Chris Lattnerb7d25532009-02-18 22:53:11 +00001039 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001040 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001041 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001042 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001043 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001044 return QualType(EXTQy, CVRQuals);
1045
Christopher Lambebb97e92008-02-04 02:31:56 +00001046 // If the base type isn't canonical, this won't be a canonical type either,
1047 // so fill in the canonical type field.
1048 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001049 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001050 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001051
Chris Lattnerb7d25532009-02-18 22:53:11 +00001052 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001053 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001054 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001055 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001056 ExtQualType *New =
1057 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001058 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001059 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001060 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001061}
1062
Chris Lattnerb7d25532009-02-18 22:53:11 +00001063QualType ASTContext::getObjCGCQualType(QualType T,
1064 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001065 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001066 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001067 return T;
1068
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001069 if (T->isPointerType()) {
1070 QualType Pointee = T->getAsPointerType()->getPointeeType();
1071 if (Pointee->isPointerType()) {
1072 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1073 return getPointerType(ResultType);
1074 }
1075 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001076 // If we are composing extended qualifiers together, merge together into one
1077 // ExtQualType node.
1078 unsigned CVRQuals = T.getCVRQualifiers();
1079 Type *TypeNode = T.getTypePtr();
1080 unsigned AddressSpace = 0;
1081
1082 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1083 // If this type already has an address space specified, it cannot get
1084 // another one.
1085 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1086 "Type cannot be in multiple addr spaces!");
1087 AddressSpace = EQT->getAddressSpace();
1088 TypeNode = EQT->getBaseType();
1089 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001090
1091 // Check if we've already instantiated an gc qual'd type of this type.
1092 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001093 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001094 void *InsertPos = 0;
1095 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001096 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001097
1098 // If the base type isn't canonical, this won't be a canonical type either,
1099 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001100 // FIXME: Isn't this also not canonical if the base type is a array
1101 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001102 QualType Canonical;
1103 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001104 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001105
Chris Lattnerb7d25532009-02-18 22:53:11 +00001106 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001107 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1108 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1109 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001110 ExtQualType *New =
1111 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001112 ExtQualTypes.InsertNode(New, InsertPos);
1113 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001114 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001115}
Chris Lattnera7674d82007-07-13 22:13:22 +00001116
Reid Spencer5f016e22007-07-11 17:01:13 +00001117/// getComplexType - Return the uniqued reference to the type for a complex
1118/// number with the specified element type.
1119QualType ASTContext::getComplexType(QualType T) {
1120 // Unique pointers, to guarantee there is only one pointer of a particular
1121 // structure.
1122 llvm::FoldingSetNodeID ID;
1123 ComplexType::Profile(ID, T);
1124
1125 void *InsertPos = 0;
1126 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1127 return QualType(CT, 0);
1128
1129 // If the pointee type isn't canonical, this won't be a canonical type either,
1130 // so fill in the canonical type field.
1131 QualType Canonical;
1132 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001133 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001134
1135 // Get the new insert position for the node we care about.
1136 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001137 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 }
Steve Narofff83820b2009-01-27 22:08:43 +00001139 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 Types.push_back(New);
1141 ComplexTypes.InsertNode(New, InsertPos);
1142 return QualType(New, 0);
1143}
1144
Eli Friedmanf98aba32009-02-13 02:31:07 +00001145QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1146 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1147 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1148 FixedWidthIntType *&Entry = Map[Width];
1149 if (!Entry)
1150 Entry = new FixedWidthIntType(Width, Signed);
1151 return QualType(Entry, 0);
1152}
Reid Spencer5f016e22007-07-11 17:01:13 +00001153
1154/// getPointerType - Return the uniqued reference to the type for a pointer to
1155/// the specified type.
1156QualType ASTContext::getPointerType(QualType T) {
1157 // Unique pointers, to guarantee there is only one pointer of a particular
1158 // structure.
1159 llvm::FoldingSetNodeID ID;
1160 PointerType::Profile(ID, T);
1161
1162 void *InsertPos = 0;
1163 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1164 return QualType(PT, 0);
1165
1166 // If the pointee type isn't canonical, this won't be a canonical type either,
1167 // so fill in the canonical type field.
1168 QualType Canonical;
1169 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001170 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001171
1172 // Get the new insert position for the node we care about.
1173 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001174 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 }
Steve Narofff83820b2009-01-27 22:08:43 +00001176 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 Types.push_back(New);
1178 PointerTypes.InsertNode(New, InsertPos);
1179 return QualType(New, 0);
1180}
1181
Steve Naroff5618bd42008-08-27 16:04:49 +00001182/// getBlockPointerType - Return the uniqued reference to the type for
1183/// a pointer to the specified block.
1184QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001185 assert(T->isFunctionType() && "block of function types only");
1186 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001187 // structure.
1188 llvm::FoldingSetNodeID ID;
1189 BlockPointerType::Profile(ID, T);
1190
1191 void *InsertPos = 0;
1192 if (BlockPointerType *PT =
1193 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1194 return QualType(PT, 0);
1195
Steve Naroff296e8d52008-08-28 19:20:44 +00001196 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001197 // type either so fill in the canonical type field.
1198 QualType Canonical;
1199 if (!T->isCanonical()) {
1200 Canonical = getBlockPointerType(getCanonicalType(T));
1201
1202 // Get the new insert position for the node we care about.
1203 BlockPointerType *NewIP =
1204 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001205 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001206 }
Steve Narofff83820b2009-01-27 22:08:43 +00001207 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001208 Types.push_back(New);
1209 BlockPointerTypes.InsertNode(New, InsertPos);
1210 return QualType(New, 0);
1211}
1212
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001213/// getLValueReferenceType - Return the uniqued reference to the type for an
1214/// lvalue reference to the specified type.
1215QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 // Unique pointers, to guarantee there is only one pointer of a particular
1217 // structure.
1218 llvm::FoldingSetNodeID ID;
1219 ReferenceType::Profile(ID, T);
1220
1221 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001222 if (LValueReferenceType *RT =
1223 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 // If the referencee type isn't canonical, this won't be a canonical type
1227 // either, so fill in the canonical type field.
1228 QualType Canonical;
1229 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001230 Canonical = getLValueReferenceType(getCanonicalType(T));
1231
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001233 LValueReferenceType *NewIP =
1234 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001235 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 }
1237
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001238 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001240 LValueReferenceTypes.InsertNode(New, InsertPos);
1241 return QualType(New, 0);
1242}
1243
1244/// getRValueReferenceType - Return the uniqued reference to the type for an
1245/// rvalue reference to the specified type.
1246QualType ASTContext::getRValueReferenceType(QualType T) {
1247 // Unique pointers, to guarantee there is only one pointer of a particular
1248 // structure.
1249 llvm::FoldingSetNodeID ID;
1250 ReferenceType::Profile(ID, T);
1251
1252 void *InsertPos = 0;
1253 if (RValueReferenceType *RT =
1254 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1255 return QualType(RT, 0);
1256
1257 // If the referencee type isn't canonical, this won't be a canonical type
1258 // either, so fill in the canonical type field.
1259 QualType Canonical;
1260 if (!T->isCanonical()) {
1261 Canonical = getRValueReferenceType(getCanonicalType(T));
1262
1263 // Get the new insert position for the node we care about.
1264 RValueReferenceType *NewIP =
1265 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1266 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1267 }
1268
1269 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1270 Types.push_back(New);
1271 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 return QualType(New, 0);
1273}
1274
Sebastian Redlf30208a2009-01-24 21:16:55 +00001275/// getMemberPointerType - Return the uniqued reference to the type for a
1276/// member pointer to the specified type, in the specified class.
1277QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1278{
1279 // Unique pointers, to guarantee there is only one pointer of a particular
1280 // structure.
1281 llvm::FoldingSetNodeID ID;
1282 MemberPointerType::Profile(ID, T, Cls);
1283
1284 void *InsertPos = 0;
1285 if (MemberPointerType *PT =
1286 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1287 return QualType(PT, 0);
1288
1289 // If the pointee or class type isn't canonical, this won't be a canonical
1290 // type either, so fill in the canonical type field.
1291 QualType Canonical;
1292 if (!T->isCanonical()) {
1293 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1294
1295 // Get the new insert position for the node we care about.
1296 MemberPointerType *NewIP =
1297 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1298 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1299 }
Steve Narofff83820b2009-01-27 22:08:43 +00001300 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001301 Types.push_back(New);
1302 MemberPointerTypes.InsertNode(New, InsertPos);
1303 return QualType(New, 0);
1304}
1305
Steve Narofffb22d962007-08-30 01:06:46 +00001306/// getConstantArrayType - Return the unique reference to the type for an
1307/// array of the specified element type.
1308QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001309 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001310 ArrayType::ArraySizeModifier ASM,
1311 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001312 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1313 "Constant array of VLAs is illegal!");
1314
Chris Lattner38aeec72009-05-13 04:12:56 +00001315 // Convert the array size into a canonical width matching the pointer size for
1316 // the target.
1317 llvm::APInt ArySize(ArySizeIn);
1318 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1319
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001321 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001322
1323 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001324 if (ConstantArrayType *ATP =
1325 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 return QualType(ATP, 0);
1327
1328 // If the element type isn't canonical, this won't be a canonical type either,
1329 // so fill in the canonical type field.
1330 QualType Canonical;
1331 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001332 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001333 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001335 ConstantArrayType *NewIP =
1336 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001337 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 }
1339
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001340 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001341 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001342 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 Types.push_back(New);
1344 return QualType(New, 0);
1345}
1346
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001347/// getVariableArrayType - Returns a non-unique reference to the type for a
1348/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001349QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1350 ArrayType::ArraySizeModifier ASM,
1351 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001352 // Since we don't unique expressions, it isn't possible to unique VLA's
1353 // that have an expression provided for their size.
1354
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001355 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001356 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001357
1358 VariableArrayTypes.push_back(New);
1359 Types.push_back(New);
1360 return QualType(New, 0);
1361}
1362
Douglas Gregor898574e2008-12-05 23:32:09 +00001363/// getDependentSizedArrayType - Returns a non-unique reference to
1364/// the type for a dependently-sized array of the specified element
1365/// type. FIXME: We will need these to be uniqued, or at least
1366/// comparable, at some point.
1367QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1368 ArrayType::ArraySizeModifier ASM,
1369 unsigned EltTypeQuals) {
1370 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1371 "Size must be type- or value-dependent!");
1372
1373 // Since we don't unique expressions, it isn't possible to unique
1374 // dependently-sized array types.
1375
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001376 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001377 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1378 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001379
1380 DependentSizedArrayTypes.push_back(New);
1381 Types.push_back(New);
1382 return QualType(New, 0);
1383}
1384
Eli Friedmanc5773c42008-02-15 18:16:39 +00001385QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1386 ArrayType::ArraySizeModifier ASM,
1387 unsigned EltTypeQuals) {
1388 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001389 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001390
1391 void *InsertPos = 0;
1392 if (IncompleteArrayType *ATP =
1393 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1394 return QualType(ATP, 0);
1395
1396 // If the element type isn't canonical, this won't be a canonical type
1397 // either, so fill in the canonical type field.
1398 QualType Canonical;
1399
1400 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001401 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001402 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001403
1404 // Get the new insert position for the node we care about.
1405 IncompleteArrayType *NewIP =
1406 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001407 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001408 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001409
Steve Narofff83820b2009-01-27 22:08:43 +00001410 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001411 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001412
1413 IncompleteArrayTypes.InsertNode(New, InsertPos);
1414 Types.push_back(New);
1415 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001416}
1417
Steve Naroff73322922007-07-18 18:00:27 +00001418/// getVectorType - Return the unique reference to a vector type of
1419/// the specified element type and size. VectorType must be a built-in type.
1420QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 BuiltinType *baseType;
1422
Chris Lattnerf52ab252008-04-06 22:59:24 +00001423 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001424 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001425
1426 // Check if we've already instantiated a vector of this type.
1427 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001428 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 void *InsertPos = 0;
1430 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1431 return QualType(VTP, 0);
1432
1433 // If the element type isn't canonical, this won't be a canonical type either,
1434 // so fill in the canonical type field.
1435 QualType Canonical;
1436 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001437 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001438
1439 // Get the new insert position for the node we care about.
1440 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001441 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 }
Steve Narofff83820b2009-01-27 22:08:43 +00001443 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 VectorTypes.InsertNode(New, InsertPos);
1445 Types.push_back(New);
1446 return QualType(New, 0);
1447}
1448
Nate Begeman213541a2008-04-18 23:10:10 +00001449/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001450/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001451QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001452 BuiltinType *baseType;
1453
Chris Lattnerf52ab252008-04-06 22:59:24 +00001454 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001455 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001456
1457 // Check if we've already instantiated a vector of this type.
1458 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001459 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001460 void *InsertPos = 0;
1461 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1462 return QualType(VTP, 0);
1463
1464 // If the element type isn't canonical, this won't be a canonical type either,
1465 // so fill in the canonical type field.
1466 QualType Canonical;
1467 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001468 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001469
1470 // Get the new insert position for the node we care about.
1471 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001473 }
Steve Narofff83820b2009-01-27 22:08:43 +00001474 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001475 VectorTypes.InsertNode(New, InsertPos);
1476 Types.push_back(New);
1477 return QualType(New, 0);
1478}
1479
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001480QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1481 Expr *SizeExpr,
1482 SourceLocation AttrLoc) {
1483 DependentSizedExtVectorType *New =
1484 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1485 SizeExpr, AttrLoc);
1486
1487 DependentSizedExtVectorTypes.push_back(New);
1488 Types.push_back(New);
1489 return QualType(New, 0);
1490}
1491
Douglas Gregor72564e72009-02-26 23:50:07 +00001492/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001493///
Douglas Gregor72564e72009-02-26 23:50:07 +00001494QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // Unique functions, to guarantee there is only one function of a particular
1496 // structure.
1497 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001498 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001499
1500 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001501 if (FunctionNoProtoType *FT =
1502 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 return QualType(FT, 0);
1504
1505 QualType Canonical;
1506 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001507 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001508
1509 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001510 FunctionNoProtoType *NewIP =
1511 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001512 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 }
1514
Douglas Gregor72564e72009-02-26 23:50:07 +00001515 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001517 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 return QualType(New, 0);
1519}
1520
1521/// getFunctionType - Return a normal function type with a typed argument
1522/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001523QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001524 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001525 unsigned TypeQuals, bool hasExceptionSpec,
1526 bool hasAnyExceptionSpec, unsigned NumExs,
1527 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // Unique functions, to guarantee there is only one function of a particular
1529 // structure.
1530 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001531 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001532 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1533 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534
1535 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001536 if (FunctionProtoType *FTP =
1537 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001539
1540 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001542 if (hasExceptionSpec)
1543 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1545 if (!ArgArray[i]->isCanonical())
1546 isCanonical = false;
1547
1548 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001549 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 QualType Canonical;
1551 if (!isCanonical) {
1552 llvm::SmallVector<QualType, 16> CanonicalArgs;
1553 CanonicalArgs.reserve(NumArgs);
1554 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001555 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001556
Chris Lattnerf52ab252008-04-06 22:59:24 +00001557 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001558 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001559 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001560
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001562 FunctionProtoType *NewIP =
1563 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001564 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001566
Douglas Gregor72564e72009-02-26 23:50:07 +00001567 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001568 // for two variable size arrays (for parameter and exception types) at the
1569 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001570 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001571 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1572 NumArgs*sizeof(QualType) +
1573 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001574 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001575 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1576 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001578 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 return QualType(FTP, 0);
1580}
1581
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001582/// getTypeDeclType - Return the unique reference to the type for the
1583/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001584QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001585 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001586 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1587
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001588 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001589 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001590 else if (isa<TemplateTypeParmDecl>(Decl)) {
1591 assert(false && "Template type parameter types are always available.");
1592 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001593 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001594
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001595 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001596 if (PrevDecl)
1597 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001598 else
1599 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001600 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001601 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1602 if (PrevDecl)
1603 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001604 else
1605 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001606 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001607 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001608 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001609
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001610 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001611 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001612}
1613
Reid Spencer5f016e22007-07-11 17:01:13 +00001614/// getTypedefType - Return the unique reference to the type for the
1615/// specified typename decl.
1616QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1617 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1618
Chris Lattnerf52ab252008-04-06 22:59:24 +00001619 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001620 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 Types.push_back(Decl->TypeForDecl);
1622 return QualType(Decl->TypeForDecl, 0);
1623}
1624
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001626/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001627QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001628 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1629
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001630 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1631 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001632 Types.push_back(Decl->TypeForDecl);
1633 return QualType(Decl->TypeForDecl, 0);
1634}
1635
Douglas Gregorfab9d672009-02-05 23:33:38 +00001636/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001637/// parameter or parameter pack with the given depth, index, and (optionally)
1638/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001639QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001640 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001641 IdentifierInfo *Name) {
1642 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001643 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001644 void *InsertPos = 0;
1645 TemplateTypeParmType *TypeParm
1646 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1647
1648 if (TypeParm)
1649 return QualType(TypeParm, 0);
1650
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001651 if (Name) {
1652 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1653 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1654 Name, Canon);
1655 } else
1656 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001657
1658 Types.push_back(TypeParm);
1659 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1660
1661 return QualType(TypeParm, 0);
1662}
1663
Douglas Gregor55f6b142009-02-09 18:46:07 +00001664QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001665ASTContext::getTemplateSpecializationType(TemplateName Template,
1666 const TemplateArgument *Args,
1667 unsigned NumArgs,
1668 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001669 if (!Canon.isNull())
1670 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001671
Douglas Gregor55f6b142009-02-09 18:46:07 +00001672 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001673 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001674
Douglas Gregor55f6b142009-02-09 18:46:07 +00001675 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001676 TemplateSpecializationType *Spec
1677 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001678
1679 if (Spec)
1680 return QualType(Spec, 0);
1681
Douglas Gregor7532dc62009-03-30 22:58:21 +00001682 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001683 sizeof(TemplateArgument) * NumArgs),
1684 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001685 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001686 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001687 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001688
1689 return QualType(Spec, 0);
1690}
1691
Douglas Gregore4e5b052009-03-19 00:18:19 +00001692QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001693ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001694 QualType NamedType) {
1695 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001696 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001697
1698 void *InsertPos = 0;
1699 QualifiedNameType *T
1700 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1701 if (T)
1702 return QualType(T, 0);
1703
Douglas Gregorab452ba2009-03-26 23:50:42 +00001704 T = new (*this) QualifiedNameType(NNS, NamedType,
1705 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001706 Types.push_back(T);
1707 QualifiedNameTypes.InsertNode(T, InsertPos);
1708 return QualType(T, 0);
1709}
1710
Douglas Gregord57959a2009-03-27 23:10:48 +00001711QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1712 const IdentifierInfo *Name,
1713 QualType Canon) {
1714 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1715
1716 if (Canon.isNull()) {
1717 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1718 if (CanonNNS != NNS)
1719 Canon = getTypenameType(CanonNNS, Name);
1720 }
1721
1722 llvm::FoldingSetNodeID ID;
1723 TypenameType::Profile(ID, NNS, Name);
1724
1725 void *InsertPos = 0;
1726 TypenameType *T
1727 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1728 if (T)
1729 return QualType(T, 0);
1730
1731 T = new (*this) TypenameType(NNS, Name, Canon);
1732 Types.push_back(T);
1733 TypenameTypes.InsertNode(T, InsertPos);
1734 return QualType(T, 0);
1735}
1736
Douglas Gregor17343172009-04-01 00:28:59 +00001737QualType
1738ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1739 const TemplateSpecializationType *TemplateId,
1740 QualType Canon) {
1741 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1742
1743 if (Canon.isNull()) {
1744 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1745 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1746 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1747 const TemplateSpecializationType *CanonTemplateId
1748 = CanonType->getAsTemplateSpecializationType();
1749 assert(CanonTemplateId &&
1750 "Canonical type must also be a template specialization type");
1751 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1752 }
1753 }
1754
1755 llvm::FoldingSetNodeID ID;
1756 TypenameType::Profile(ID, NNS, TemplateId);
1757
1758 void *InsertPos = 0;
1759 TypenameType *T
1760 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1761 if (T)
1762 return QualType(T, 0);
1763
1764 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1765 Types.push_back(T);
1766 TypenameTypes.InsertNode(T, InsertPos);
1767 return QualType(T, 0);
1768}
1769
Chris Lattner88cb27a2008-04-07 04:56:42 +00001770/// CmpProtocolNames - Comparison predicate for sorting protocols
1771/// alphabetically.
1772static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1773 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001774 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001775}
1776
1777static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1778 unsigned &NumProtocols) {
1779 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1780
1781 // Sort protocols, keyed by name.
1782 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1783
1784 // Remove duplicates.
1785 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1786 NumProtocols = ProtocolsEnd-Protocols;
1787}
1788
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001789/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1790/// the given interface decl and the conforming protocol list.
1791QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1792 ObjCProtocolDecl **Protocols,
1793 unsigned NumProtocols) {
1794 // Sort the protocol list alphabetically to canonicalize it.
1795 if (NumProtocols)
1796 SortAndUniqueProtocols(Protocols, NumProtocols);
1797
1798 llvm::FoldingSetNodeID ID;
1799 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1800
1801 void *InsertPos = 0;
1802 if (ObjCObjectPointerType *QT =
1803 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1804 return QualType(QT, 0);
1805
1806 // No Match;
1807 ObjCObjectPointerType *QType =
1808 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1809
1810 Types.push_back(QType);
1811 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1812 return QualType(QType, 0);
1813}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001814
Chris Lattner065f0d72008-04-07 04:44:08 +00001815/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1816/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001817QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1818 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001819 // Sort the protocol list alphabetically to canonicalize it.
1820 SortAndUniqueProtocols(Protocols, NumProtocols);
1821
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001822 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001823 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001824
1825 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001826 if (ObjCQualifiedInterfaceType *QT =
1827 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001828 return QualType(QT, 0);
1829
1830 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001831 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001832 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001833
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001834 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001835 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001836 return QualType(QType, 0);
1837}
1838
Douglas Gregor72564e72009-02-26 23:50:07 +00001839/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1840/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001841/// multiple declarations that refer to "typeof(x)" all contain different
1842/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1843/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001844QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001845 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001846 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001847 Types.push_back(toe);
1848 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001849}
1850
Steve Naroff9752f252007-08-01 18:02:17 +00001851/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1852/// TypeOfType AST's. The only motivation to unique these nodes would be
1853/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1854/// an issue. This doesn't effect the type checker, since it operates
1855/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001856QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001857 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001858 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001859 Types.push_back(tot);
1860 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001861}
1862
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001863/// getDecltypeForExpr - Given an expr, will return the decltype for that
1864/// expression, according to the rules in C++0x [dcl.type.simple]p4
1865static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001866 if (e->isTypeDependent())
1867 return Context.DependentTy;
1868
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001869 // If e is an id expression or a class member access, decltype(e) is defined
1870 // as the type of the entity named by e.
1871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1872 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1873 return VD->getType();
1874 }
1875 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1876 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1877 return FD->getType();
1878 }
1879 // If e is a function call or an invocation of an overloaded operator,
1880 // (parentheses around e are ignored), decltype(e) is defined as the
1881 // return type of that function.
1882 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1883 return CE->getCallReturnType();
1884
1885 QualType T = e->getType();
1886
1887 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1888 // defined as T&, otherwise decltype(e) is defined as T.
1889 if (e->isLvalue(Context) == Expr::LV_Valid)
1890 T = Context.getLValueReferenceType(T);
1891
1892 return T;
1893}
1894
Anders Carlsson395b4752009-06-24 19:06:50 +00001895/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1896/// DecltypeType AST's. The only motivation to unique these nodes would be
1897/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1898/// an issue. This doesn't effect the type checker, since it operates
1899/// on canonical type's (which are always unique).
1900QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001901 QualType T = getDecltypeForExpr(e, *this);
1902 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001903 Types.push_back(dt);
1904 return QualType(dt, 0);
1905}
1906
Reid Spencer5f016e22007-07-11 17:01:13 +00001907/// getTagDeclType - Return the unique reference to the type for the
1908/// specified TagDecl (struct/union/class/enum) decl.
1909QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001910 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001911 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001912}
1913
1914/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1915/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1916/// needs to agree with the definition in <stddef.h>.
1917QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001918 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001919}
1920
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001921/// getSignedWCharType - Return the type of "signed wchar_t".
1922/// Used when in C++, as a GCC extension.
1923QualType ASTContext::getSignedWCharType() const {
1924 // FIXME: derive from "Target" ?
1925 return WCharTy;
1926}
1927
1928/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1929/// Used when in C++, as a GCC extension.
1930QualType ASTContext::getUnsignedWCharType() const {
1931 // FIXME: derive from "Target" ?
1932 return UnsignedIntTy;
1933}
1934
Chris Lattner8b9023b2007-07-13 03:05:23 +00001935/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1936/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1937QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001938 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001939}
1940
Chris Lattnere6327742008-04-02 05:18:44 +00001941//===----------------------------------------------------------------------===//
1942// Type Operators
1943//===----------------------------------------------------------------------===//
1944
Chris Lattner77c96472008-04-06 22:41:35 +00001945/// getCanonicalType - Return the canonical (structural) type corresponding to
1946/// the specified potentially non-canonical type. The non-canonical version
1947/// of a type may have many "decorated" versions of types. Decorators can
1948/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1949/// to be free of any of these, allowing two canonical types to be compared
1950/// for exact equality with a simple pointer comparison.
1951QualType ASTContext::getCanonicalType(QualType T) {
1952 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001953
1954 // If the result has type qualifiers, make sure to canonicalize them as well.
1955 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1956 if (TypeQuals == 0) return CanType;
1957
1958 // If the type qualifiers are on an array type, get the canonical type of the
1959 // array with the qualifiers applied to the element type.
1960 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1961 if (!AT)
1962 return CanType.getQualifiedType(TypeQuals);
1963
1964 // Get the canonical version of the element with the extra qualifiers on it.
1965 // This can recursively sink qualifiers through multiple levels of arrays.
1966 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1967 NewEltTy = getCanonicalType(NewEltTy);
1968
1969 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1970 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1971 CAT->getIndexTypeQualifier());
1972 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1973 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1974 IAT->getIndexTypeQualifier());
1975
Douglas Gregor898574e2008-12-05 23:32:09 +00001976 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1977 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1978 DSAT->getSizeModifier(),
1979 DSAT->getIndexTypeQualifier());
1980
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001981 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1982 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1983 VAT->getSizeModifier(),
1984 VAT->getIndexTypeQualifier());
1985}
1986
Douglas Gregor7da97d02009-05-10 22:57:19 +00001987Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001988 if (!D)
1989 return 0;
1990
Douglas Gregor7da97d02009-05-10 22:57:19 +00001991 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1992 QualType T = getTagDeclType(Tag);
1993 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1994 ->getDecl());
1995 }
1996
1997 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1998 while (Template->getPreviousDeclaration())
1999 Template = Template->getPreviousDeclaration();
2000 return Template;
2001 }
2002
2003 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2004 while (Function->getPreviousDeclaration())
2005 Function = Function->getPreviousDeclaration();
2006 return const_cast<FunctionDecl *>(Function);
2007 }
2008
Douglas Gregor127102b2009-06-29 20:59:39 +00002009 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2010 while (FunTmpl->getPreviousDeclaration())
2011 FunTmpl = FunTmpl->getPreviousDeclaration();
2012 return FunTmpl;
2013 }
2014
Douglas Gregor7da97d02009-05-10 22:57:19 +00002015 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2016 while (Var->getPreviousDeclaration())
2017 Var = Var->getPreviousDeclaration();
2018 return const_cast<VarDecl *>(Var);
2019 }
2020
2021 return D;
2022}
2023
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002024TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2025 // If this template name refers to a template, the canonical
2026 // template name merely stores the template itself.
2027 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002028 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002029
2030 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2031 assert(DTN && "Non-dependent template names must refer to template decls.");
2032 return DTN->CanonicalTemplateName;
2033}
2034
Douglas Gregord57959a2009-03-27 23:10:48 +00002035NestedNameSpecifier *
2036ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2037 if (!NNS)
2038 return 0;
2039
2040 switch (NNS->getKind()) {
2041 case NestedNameSpecifier::Identifier:
2042 // Canonicalize the prefix but keep the identifier the same.
2043 return NestedNameSpecifier::Create(*this,
2044 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2045 NNS->getAsIdentifier());
2046
2047 case NestedNameSpecifier::Namespace:
2048 // A namespace is canonical; build a nested-name-specifier with
2049 // this namespace and no prefix.
2050 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2051
2052 case NestedNameSpecifier::TypeSpec:
2053 case NestedNameSpecifier::TypeSpecWithTemplate: {
2054 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2055 NestedNameSpecifier *Prefix = 0;
2056
2057 // FIXME: This isn't the right check!
2058 if (T->isDependentType())
2059 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2060
2061 return NestedNameSpecifier::Create(*this, Prefix,
2062 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2063 T.getTypePtr());
2064 }
2065
2066 case NestedNameSpecifier::Global:
2067 // The global specifier is canonical and unique.
2068 return NNS;
2069 }
2070
2071 // Required to silence a GCC warning
2072 return 0;
2073}
2074
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002075
2076const ArrayType *ASTContext::getAsArrayType(QualType T) {
2077 // Handle the non-qualified case efficiently.
2078 if (T.getCVRQualifiers() == 0) {
2079 // Handle the common positive case fast.
2080 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2081 return AT;
2082 }
2083
2084 // Handle the common negative case fast, ignoring CVR qualifiers.
2085 QualType CType = T->getCanonicalTypeInternal();
2086
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002087 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002088 // test.
2089 if (!isa<ArrayType>(CType) &&
2090 !isa<ArrayType>(CType.getUnqualifiedType()))
2091 return 0;
2092
2093 // Apply any CVR qualifiers from the array type to the element type. This
2094 // implements C99 6.7.3p8: "If the specification of an array type includes
2095 // any type qualifiers, the element type is so qualified, not the array type."
2096
2097 // If we get here, we either have type qualifiers on the type, or we have
2098 // sugar such as a typedef in the way. If we have type qualifiers on the type
2099 // we must propagate them down into the elemeng type.
2100 unsigned CVRQuals = T.getCVRQualifiers();
2101 unsigned AddrSpace = 0;
2102 Type *Ty = T.getTypePtr();
2103
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002104 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002105 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002106 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2107 AddrSpace = EXTQT->getAddressSpace();
2108 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002109 } else {
2110 T = Ty->getDesugaredType();
2111 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2112 break;
2113 CVRQuals |= T.getCVRQualifiers();
2114 Ty = T.getTypePtr();
2115 }
2116 }
2117
2118 // If we have a simple case, just return now.
2119 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2120 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2121 return ATy;
2122
2123 // Otherwise, we have an array and we have qualifiers on it. Push the
2124 // qualifiers into the array element type and return a new array type.
2125 // Get the canonical version of the element with the extra qualifiers on it.
2126 // This can recursively sink qualifiers through multiple levels of arrays.
2127 QualType NewEltTy = ATy->getElementType();
2128 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002129 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002130 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2131
2132 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2133 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2134 CAT->getSizeModifier(),
2135 CAT->getIndexTypeQualifier()));
2136 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2137 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2138 IAT->getSizeModifier(),
2139 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002140
Douglas Gregor898574e2008-12-05 23:32:09 +00002141 if (const DependentSizedArrayType *DSAT
2142 = dyn_cast<DependentSizedArrayType>(ATy))
2143 return cast<ArrayType>(
2144 getDependentSizedArrayType(NewEltTy,
2145 DSAT->getSizeExpr(),
2146 DSAT->getSizeModifier(),
2147 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002148
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002149 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2150 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
2151 VAT->getSizeModifier(),
2152 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00002153}
2154
2155
Chris Lattnere6327742008-04-02 05:18:44 +00002156/// getArrayDecayedType - Return the properly qualified result of decaying the
2157/// specified array type to a pointer. This operation is non-trivial when
2158/// handling typedefs etc. The canonical type of "T" must be an array type,
2159/// this returns a pointer to a properly qualified element of the array.
2160///
2161/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2162QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002163 // Get the element type with 'getAsArrayType' so that we don't lose any
2164 // typedefs in the element type of the array. This also handles propagation
2165 // of type qualifiers from the array type into the element type if present
2166 // (C99 6.7.3p8).
2167 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2168 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002169
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002170 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002171
2172 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002173 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002174}
2175
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002176QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002177 QualType ElemTy = VAT->getElementType();
2178
2179 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2180 return getBaseElementType(VAT);
2181
2182 return ElemTy;
2183}
2184
Reid Spencer5f016e22007-07-11 17:01:13 +00002185/// getFloatingRank - Return a relative rank for floating point types.
2186/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002187static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002188 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002189 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002190
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002191 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002192 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002193 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 case BuiltinType::Float: return FloatRank;
2195 case BuiltinType::Double: return DoubleRank;
2196 case BuiltinType::LongDouble: return LongDoubleRank;
2197 }
2198}
2199
Steve Naroff716c7302007-08-27 01:41:48 +00002200/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2201/// point or a complex type (based on typeDomain/typeSize).
2202/// 'typeDomain' is a real floating point or complex type.
2203/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002204QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2205 QualType Domain) const {
2206 FloatingRank EltRank = getFloatingRank(Size);
2207 if (Domain->isComplexType()) {
2208 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002209 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002210 case FloatRank: return FloatComplexTy;
2211 case DoubleRank: return DoubleComplexTy;
2212 case LongDoubleRank: return LongDoubleComplexTy;
2213 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 }
Chris Lattner1361b112008-04-06 23:58:54 +00002215
2216 assert(Domain->isRealFloatingType() && "Unknown domain!");
2217 switch (EltRank) {
2218 default: assert(0 && "getFloatingRank(): illegal value for rank");
2219 case FloatRank: return FloatTy;
2220 case DoubleRank: return DoubleTy;
2221 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002223}
2224
Chris Lattner7cfeb082008-04-06 23:55:33 +00002225/// getFloatingTypeOrder - Compare the rank of the two specified floating
2226/// point types, ignoring the domain of the type (i.e. 'double' ==
2227/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2228/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002229int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2230 FloatingRank LHSR = getFloatingRank(LHS);
2231 FloatingRank RHSR = getFloatingRank(RHS);
2232
2233 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002234 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002235 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002236 return 1;
2237 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002238}
2239
Chris Lattnerf52ab252008-04-06 22:59:24 +00002240/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2241/// routine will assert if passed a built-in type that isn't an integer or enum,
2242/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002243unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002244 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002245 if (EnumType* ET = dyn_cast<EnumType>(T))
2246 T = ET->getDecl()->getIntegerType().getTypePtr();
2247
Eli Friedmana3426752009-07-05 23:44:27 +00002248 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2249 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2250
Eli Friedmanf98aba32009-02-13 02:31:07 +00002251 // There are two things which impact the integer rank: the width, and
2252 // the ordering of builtins. The builtin ordering is encoded in the
2253 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002254 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002255 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002256
Chris Lattnerf52ab252008-04-06 22:59:24 +00002257 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002258 default: assert(0 && "getIntegerRank(): not a built-in integer");
2259 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002260 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002261 case BuiltinType::Char_S:
2262 case BuiltinType::Char_U:
2263 case BuiltinType::SChar:
2264 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002265 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002266 case BuiltinType::Short:
2267 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002268 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002269 case BuiltinType::Int:
2270 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002271 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002272 case BuiltinType::Long:
2273 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002274 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002275 case BuiltinType::LongLong:
2276 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002277 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002278 case BuiltinType::Int128:
2279 case BuiltinType::UInt128:
2280 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002281 }
2282}
2283
Chris Lattner7cfeb082008-04-06 23:55:33 +00002284/// getIntegerTypeOrder - Returns the highest ranked integer type:
2285/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2286/// LHS < RHS, return -1.
2287int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002288 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2289 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002290 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002291
Chris Lattnerf52ab252008-04-06 22:59:24 +00002292 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2293 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002294
Chris Lattner7cfeb082008-04-06 23:55:33 +00002295 unsigned LHSRank = getIntegerRank(LHSC);
2296 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002297
Chris Lattner7cfeb082008-04-06 23:55:33 +00002298 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2299 if (LHSRank == RHSRank) return 0;
2300 return LHSRank > RHSRank ? 1 : -1;
2301 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002302
Chris Lattner7cfeb082008-04-06 23:55:33 +00002303 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2304 if (LHSUnsigned) {
2305 // If the unsigned [LHS] type is larger, return it.
2306 if (LHSRank >= RHSRank)
2307 return 1;
2308
2309 // If the signed type can represent all values of the unsigned type, it
2310 // wins. Because we are dealing with 2's complement and types that are
2311 // powers of two larger than each other, this is always safe.
2312 return -1;
2313 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002314
Chris Lattner7cfeb082008-04-06 23:55:33 +00002315 // If the unsigned [RHS] type is larger, return it.
2316 if (RHSRank >= LHSRank)
2317 return -1;
2318
2319 // If the signed type can represent all values of the unsigned type, it
2320 // wins. Because we are dealing with 2's complement and types that are
2321 // powers of two larger than each other, this is always safe.
2322 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002323}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002324
2325// getCFConstantStringType - Return the type used for constant CFStrings.
2326QualType ASTContext::getCFConstantStringType() {
2327 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002328 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002329 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002330 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002331 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002332
2333 // const int *isa;
2334 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002335 // int flags;
2336 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002337 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002338 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002339 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002340 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002341
Anders Carlsson71993dd2007-08-17 05:31:46 +00002342 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002343 for (unsigned i = 0; i < 4; ++i) {
2344 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2345 SourceLocation(), 0,
2346 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002347 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002348 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002349 }
2350
2351 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002352 }
2353
2354 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002355}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002356
Douglas Gregor319ac892009-04-23 22:29:11 +00002357void ASTContext::setCFConstantStringType(QualType T) {
2358 const RecordType *Rec = T->getAsRecordType();
2359 assert(Rec && "Invalid CFConstantStringType");
2360 CFConstantStringTypeDecl = Rec->getDecl();
2361}
2362
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002363QualType ASTContext::getObjCFastEnumerationStateType()
2364{
2365 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002366 ObjCFastEnumerationStateTypeDecl =
2367 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2368 &Idents.get("__objcFastEnumerationState"));
2369
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002370 QualType FieldTypes[] = {
2371 UnsignedLongTy,
2372 getPointerType(ObjCIdType),
2373 getPointerType(UnsignedLongTy),
2374 getConstantArrayType(UnsignedLongTy,
2375 llvm::APInt(32, 5), ArrayType::Normal, 0)
2376 };
2377
Douglas Gregor44b43212008-12-11 16:49:14 +00002378 for (size_t i = 0; i < 4; ++i) {
2379 FieldDecl *Field = FieldDecl::Create(*this,
2380 ObjCFastEnumerationStateTypeDecl,
2381 SourceLocation(), 0,
2382 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002383 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002384 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002385 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002386
Douglas Gregor44b43212008-12-11 16:49:14 +00002387 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002388 }
2389
2390 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2391}
2392
Douglas Gregor319ac892009-04-23 22:29:11 +00002393void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2394 const RecordType *Rec = T->getAsRecordType();
2395 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2396 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2397}
2398
Anders Carlssone8c49532007-10-29 06:33:42 +00002399// This returns true if a type has been typedefed to BOOL:
2400// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002401static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002402 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002403 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2404 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002405
2406 return false;
2407}
2408
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002409/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002410/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002412 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002413
2414 // Make all integer and enum types at least as large as an int
2415 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002416 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002417 // Treat arrays as pointers, since that's how they're passed in.
2418 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002419 sz = getTypeSize(VoidPtrTy);
2420 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002421}
2422
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002423/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002424/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002425void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002426 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002427 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002428 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002429 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002430 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002431 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002432 // Compute size of all parameters.
2433 // Start with computing size of a pointer in number of bytes.
2434 // FIXME: There might(should) be a better way of doing this computation!
2435 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002436 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002437 // The first two arguments (self and _cmd) are pointers; account for
2438 // their size.
2439 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002440 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2441 E = Decl->param_end(); PI != E; ++PI) {
2442 QualType PType = (*PI)->getType();
2443 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002444 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002445 ParmOffset += sz;
2446 }
2447 S += llvm::utostr(ParmOffset);
2448 S += "@0:";
2449 S += llvm::utostr(PtrSize);
2450
2451 // Argument types.
2452 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002453 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2454 E = Decl->param_end(); PI != E; ++PI) {
2455 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002456 QualType PType = PVDecl->getOriginalType();
2457 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002458 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2459 // Use array's original type only if it has known number of
2460 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002461 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002462 PType = PVDecl->getType();
2463 } else if (PType->isFunctionType())
2464 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002465 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002466 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002467 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002468 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002469 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002470 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002471 }
2472}
2473
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002474/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002475/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002476/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2477/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002478/// Property attributes are stored as a comma-delimited C string. The simple
2479/// attributes readonly and bycopy are encoded as single characters. The
2480/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2481/// encoded as single characters, followed by an identifier. Property types
2482/// are also encoded as a parametrized attribute. The characters used to encode
2483/// these attributes are defined by the following enumeration:
2484/// @code
2485/// enum PropertyAttributes {
2486/// kPropertyReadOnly = 'R', // property is read-only.
2487/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2488/// kPropertyByref = '&', // property is a reference to the value last assigned
2489/// kPropertyDynamic = 'D', // property is dynamic
2490/// kPropertyGetter = 'G', // followed by getter selector name
2491/// kPropertySetter = 'S', // followed by setter selector name
2492/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2493/// kPropertyType = 't' // followed by old-style type encoding.
2494/// kPropertyWeak = 'W' // 'weak' property
2495/// kPropertyStrong = 'P' // property GC'able
2496/// kPropertyNonAtomic = 'N' // property non-atomic
2497/// };
2498/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002499void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2500 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002501 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002502 // Collect information from the property implementation decl(s).
2503 bool Dynamic = false;
2504 ObjCPropertyImplDecl *SynthesizePID = 0;
2505
2506 // FIXME: Duplicated code due to poor abstraction.
2507 if (Container) {
2508 if (const ObjCCategoryImplDecl *CID =
2509 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2510 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002511 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002512 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002513 ObjCPropertyImplDecl *PID = *i;
2514 if (PID->getPropertyDecl() == PD) {
2515 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2516 Dynamic = true;
2517 } else {
2518 SynthesizePID = PID;
2519 }
2520 }
2521 }
2522 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002523 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002524 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002525 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002526 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002527 ObjCPropertyImplDecl *PID = *i;
2528 if (PID->getPropertyDecl() == PD) {
2529 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2530 Dynamic = true;
2531 } else {
2532 SynthesizePID = PID;
2533 }
2534 }
2535 }
2536 }
2537 }
2538
2539 // FIXME: This is not very efficient.
2540 S = "T";
2541
2542 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002543 // GCC has some special rules regarding encoding of properties which
2544 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002545 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002546 true /* outermost type */,
2547 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002548
2549 if (PD->isReadOnly()) {
2550 S += ",R";
2551 } else {
2552 switch (PD->getSetterKind()) {
2553 case ObjCPropertyDecl::Assign: break;
2554 case ObjCPropertyDecl::Copy: S += ",C"; break;
2555 case ObjCPropertyDecl::Retain: S += ",&"; break;
2556 }
2557 }
2558
2559 // It really isn't clear at all what this means, since properties
2560 // are "dynamic by default".
2561 if (Dynamic)
2562 S += ",D";
2563
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002564 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2565 S += ",N";
2566
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002567 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2568 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002569 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002570 }
2571
2572 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2573 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002574 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002575 }
2576
2577 if (SynthesizePID) {
2578 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2579 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002580 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002581 }
2582
2583 // FIXME: OBJCGC: weak & strong
2584}
2585
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002586/// getLegacyIntegralTypeEncoding -
2587/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002588/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002589/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2590///
2591void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2592 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2593 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002594 if (BT->getKind() == BuiltinType::ULong &&
2595 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002596 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002597 else
2598 if (BT->getKind() == BuiltinType::Long &&
2599 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002600 PointeeTy = IntTy;
2601 }
2602 }
2603}
2604
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002605void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002606 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002607 // We follow the behavior of gcc, expanding structures which are
2608 // directly pointed to, and expanding embedded structures. Note that
2609 // these rules are sufficient to prevent recursive encoding of the
2610 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002611 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2612 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002613}
2614
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002615static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002616 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002617 const Expr *E = FD->getBitWidth();
2618 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2619 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002620 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002621 S += 'b';
2622 S += llvm::utostr(N);
2623}
2624
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002625void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2626 bool ExpandPointedToStructures,
2627 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002628 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002629 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002630 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002631 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002632 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002633 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002634 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002635 else {
2636 char encoding;
2637 switch (BT->getKind()) {
2638 default: assert(0 && "Unhandled builtin type kind");
2639 case BuiltinType::Void: encoding = 'v'; break;
2640 case BuiltinType::Bool: encoding = 'B'; break;
2641 case BuiltinType::Char_U:
2642 case BuiltinType::UChar: encoding = 'C'; break;
2643 case BuiltinType::UShort: encoding = 'S'; break;
2644 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002645 case BuiltinType::ULong:
2646 encoding =
2647 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2648 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002649 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002650 case BuiltinType::ULongLong: encoding = 'Q'; break;
2651 case BuiltinType::Char_S:
2652 case BuiltinType::SChar: encoding = 'c'; break;
2653 case BuiltinType::Short: encoding = 's'; break;
2654 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002655 case BuiltinType::Long:
2656 encoding =
2657 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2658 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002659 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002660 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002661 case BuiltinType::Float: encoding = 'f'; break;
2662 case BuiltinType::Double: encoding = 'd'; break;
2663 case BuiltinType::LongDouble: encoding = 'd'; break;
2664 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002665
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002666 S += encoding;
2667 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002668 } else if (const ComplexType *CT = T->getAsComplexType()) {
2669 S += 'j';
2670 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2671 false);
2672 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002673 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2674 ExpandPointedToStructures,
2675 ExpandStructures, FD);
2676 if (FD || EncodingProperty) {
2677 // Note that we do extended encoding of protocol qualifer list
2678 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002679 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002680 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002681 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002682 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002683 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002684 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002685 S += '>';
2686 }
2687 S += '"';
2688 }
2689 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002690 }
2691 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002692 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002693 bool isReadOnly = false;
2694 // For historical/compatibility reasons, the read-only qualifier of the
2695 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2696 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2697 // Also, do not emit the 'r' for anything but the outermost type!
2698 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2699 if (OutermostType && T.isConstQualified()) {
2700 isReadOnly = true;
2701 S += 'r';
2702 }
2703 }
2704 else if (OutermostType) {
2705 QualType P = PointeeTy;
2706 while (P->getAsPointerType())
2707 P = P->getAsPointerType()->getPointeeType();
2708 if (P.isConstQualified()) {
2709 isReadOnly = true;
2710 S += 'r';
2711 }
2712 }
2713 if (isReadOnly) {
2714 // Another legacy compatibility encoding. Some ObjC qualifier and type
2715 // combinations need to be rearranged.
2716 // Rewrite "in const" from "nr" to "rn"
2717 const char * s = S.c_str();
2718 int len = S.length();
2719 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2720 std::string replace = "rn";
2721 S.replace(S.end()-2, S.end(), replace);
2722 }
2723 }
Steve Naroff389bf462009-02-12 17:52:19 +00002724 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002725 S += '@';
2726 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002727 }
2728 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002729 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002730 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002731 // Another historical/compatibility reason.
2732 // We encode the underlying type which comes out as
2733 // {...};
2734 S += '^';
2735 getObjCEncodingForTypeImpl(PointeeTy, S,
2736 false, ExpandPointedToStructures,
2737 NULL);
2738 return;
2739 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002740 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002741 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002742 const ObjCInterfaceType *OIT =
2743 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002744 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002745 S += '"';
2746 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002747 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2748 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002749 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002750 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002751 S += '>';
2752 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002753 S += '"';
2754 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002755 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002756 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002757 S += '#';
2758 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002759 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002760 S += ':';
2761 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002762 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002763
2764 if (PointeeTy->isCharType()) {
2765 // char pointer types should be encoded as '*' unless it is a
2766 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002767 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002768 S += '*';
2769 return;
2770 }
2771 }
2772
2773 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002774 getLegacyIntegralTypeEncoding(PointeeTy);
2775
2776 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002777 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002778 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002779 } else if (const ArrayType *AT =
2780 // Ignore type qualifiers etc.
2781 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002782 if (isa<IncompleteArrayType>(AT)) {
2783 // Incomplete arrays are encoded as a pointer to the array element.
2784 S += '^';
2785
2786 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2787 false, ExpandStructures, FD);
2788 } else {
2789 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002790
Anders Carlsson559a8332009-02-22 01:38:57 +00002791 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2792 S += llvm::utostr(CAT->getSize().getZExtValue());
2793 else {
2794 //Variable length arrays are encoded as a regular array with 0 elements.
2795 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2796 S += '0';
2797 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002798
Anders Carlsson559a8332009-02-22 01:38:57 +00002799 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2800 false, ExpandStructures, FD);
2801 S += ']';
2802 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002803 } else if (T->getAsFunctionType()) {
2804 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002805 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002806 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002807 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002808 // Anonymous structures print as '?'
2809 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2810 S += II->getName();
2811 } else {
2812 S += '?';
2813 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002814 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002815 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002816 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2817 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002818 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002819 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002820 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002821 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002822 S += '"';
2823 }
2824
2825 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002826 if (Field->isBitField()) {
2827 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2828 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002829 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002830 QualType qt = Field->getType();
2831 getLegacyIntegralTypeEncoding(qt);
2832 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002833 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002834 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002835 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002836 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002837 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002838 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002839 if (FD && FD->isBitField())
2840 EncodeBitField(this, S, FD);
2841 else
2842 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002843 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002844 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002845 } else if (T->isObjCInterfaceType()) {
2846 // @encode(class_name)
2847 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2848 S += '{';
2849 const IdentifierInfo *II = OI->getIdentifier();
2850 S += II->getName();
2851 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002852 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002853 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002854 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002855 if (RecFields[i]->isBitField())
2856 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2857 RecFields[i]);
2858 else
2859 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2860 FD);
2861 }
2862 S += '}';
2863 }
2864 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002865 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002866}
2867
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002868void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002869 std::string& S) const {
2870 if (QT & Decl::OBJC_TQ_In)
2871 S += 'n';
2872 if (QT & Decl::OBJC_TQ_Inout)
2873 S += 'N';
2874 if (QT & Decl::OBJC_TQ_Out)
2875 S += 'o';
2876 if (QT & Decl::OBJC_TQ_Bycopy)
2877 S += 'O';
2878 if (QT & Decl::OBJC_TQ_Byref)
2879 S += 'R';
2880 if (QT & Decl::OBJC_TQ_Oneway)
2881 S += 'V';
2882}
2883
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002884void ASTContext::setBuiltinVaListType(QualType T)
2885{
2886 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2887
2888 BuiltinVaListType = T;
2889}
2890
Douglas Gregor319ac892009-04-23 22:29:11 +00002891void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002892{
Douglas Gregor319ac892009-04-23 22:29:11 +00002893 ObjCIdType = T;
2894
2895 const TypedefType *TT = T->getAsTypedefType();
2896 if (!TT)
2897 return;
2898
2899 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002900
2901 // typedef struct objc_object *id;
2902 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002903 // User error - caller will issue diagnostics.
2904 if (!ptr)
2905 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002906 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002907 // User error - caller will issue diagnostics.
2908 if (!rec)
2909 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002910 IdStructType = rec;
2911}
2912
Douglas Gregor319ac892009-04-23 22:29:11 +00002913void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002914{
Douglas Gregor319ac892009-04-23 22:29:11 +00002915 ObjCSelType = T;
2916
2917 const TypedefType *TT = T->getAsTypedefType();
2918 if (!TT)
2919 return;
2920 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002921
2922 // typedef struct objc_selector *SEL;
2923 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002924 if (!ptr)
2925 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002926 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002927 if (!rec)
2928 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002929 SelStructType = rec;
2930}
2931
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002932void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002933{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002934 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002935}
2936
Douglas Gregor319ac892009-04-23 22:29:11 +00002937void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002938{
Douglas Gregor319ac892009-04-23 22:29:11 +00002939 ObjCClassType = T;
2940
2941 const TypedefType *TT = T->getAsTypedefType();
2942 if (!TT)
2943 return;
2944 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002945
2946 // typedef struct objc_class *Class;
2947 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2948 assert(ptr && "'Class' incorrectly typed");
2949 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2950 assert(rec && "'Class' incorrectly typed");
2951 ClassStructType = rec;
2952}
2953
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002954void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2955 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002956 "'NSConstantString' type already set!");
2957
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002958 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002959}
2960
Douglas Gregor7532dc62009-03-30 22:58:21 +00002961/// \brief Retrieve the template name that represents a qualified
2962/// template name such as \c std::vector.
2963TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2964 bool TemplateKeyword,
2965 TemplateDecl *Template) {
2966 llvm::FoldingSetNodeID ID;
2967 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2968
2969 void *InsertPos = 0;
2970 QualifiedTemplateName *QTN =
2971 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2972 if (!QTN) {
2973 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2974 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2975 }
2976
2977 return TemplateName(QTN);
2978}
2979
2980/// \brief Retrieve the template name that represents a dependent
2981/// template name such as \c MetaFun::template apply.
2982TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2983 const IdentifierInfo *Name) {
2984 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2985
2986 llvm::FoldingSetNodeID ID;
2987 DependentTemplateName::Profile(ID, NNS, Name);
2988
2989 void *InsertPos = 0;
2990 DependentTemplateName *QTN =
2991 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2992
2993 if (QTN)
2994 return TemplateName(QTN);
2995
2996 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2997 if (CanonNNS == NNS) {
2998 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2999 } else {
3000 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3001 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3002 }
3003
3004 DependentTemplateNames.InsertNode(QTN, InsertPos);
3005 return TemplateName(QTN);
3006}
3007
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003008/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003009/// TargetInfo, produce the corresponding type. The unsigned @p Type
3010/// is actually a value of type @c TargetInfo::IntType.
3011QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003012 switch (Type) {
3013 case TargetInfo::NoInt: return QualType();
3014 case TargetInfo::SignedShort: return ShortTy;
3015 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3016 case TargetInfo::SignedInt: return IntTy;
3017 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3018 case TargetInfo::SignedLong: return LongTy;
3019 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3020 case TargetInfo::SignedLongLong: return LongLongTy;
3021 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3022 }
3023
3024 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003025 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003026}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003027
3028//===----------------------------------------------------------------------===//
3029// Type Predicates.
3030//===----------------------------------------------------------------------===//
3031
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003032/// isObjCNSObjectType - Return true if this is an NSObject object using
3033/// NSObject attribute on a c-style pointer type.
3034/// FIXME - Make it work directly on types.
3035///
3036bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3037 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3038 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003039 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003040 return true;
3041 }
3042 return false;
3043}
3044
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003045/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3046/// to an object type. This includes "id" and "Class" (two 'special' pointers
3047/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3048/// ID type).
3049bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00003050 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003051 return true;
3052
Steve Naroff6ae98502008-10-21 18:24:04 +00003053 // Blocks are objects.
3054 if (Ty->isBlockPointerType())
3055 return true;
3056
3057 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00003058 const PointerType *PT = Ty->getAsPointerType();
3059 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003060 return false;
3061
Chris Lattner16ede0e2009-04-12 23:51:02 +00003062 // If this a pointer to an interface (e.g. NSString*), it is ok.
3063 if (PT->getPointeeType()->isObjCInterfaceType() ||
3064 // If is has NSObject attribute, OK as well.
3065 isObjCNSObjectType(Ty))
3066 return true;
3067
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003068 // Check to see if this is 'id' or 'Class', both of which are typedefs for
3069 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00003070 // underlying type. Iteratively strip off typedefs so that we can handle
3071 // typedefs of typedefs.
3072 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3073 if (Ty.getUnqualifiedType() == getObjCIdType() ||
3074 Ty.getUnqualifiedType() == getObjCClassType())
3075 return true;
3076
3077 Ty = TDT->getDecl()->getUnderlyingType();
3078 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003079
Chris Lattner16ede0e2009-04-12 23:51:02 +00003080 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003081}
3082
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003083/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3084/// garbage collection attribute.
3085///
3086QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003087 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003088 if (getLangOptions().ObjC1 &&
3089 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003090 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003091 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003092 // (or pointers to them) be treated as though they were declared
3093 // as __strong.
3094 if (GCAttrs == QualType::GCNone) {
3095 if (isObjCObjectPointerType(Ty))
3096 GCAttrs = QualType::Strong;
3097 else if (Ty->isPointerType())
3098 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3099 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003100 // Non-pointers have none gc'able attribute regardless of the attribute
3101 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003102 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003103 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003104 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003105 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003106}
3107
Chris Lattner6ac46a42008-04-07 06:51:04 +00003108//===----------------------------------------------------------------------===//
3109// Type Compatibility Testing
3110//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003111
Chris Lattner6ac46a42008-04-07 06:51:04 +00003112/// areCompatVectorTypes - Return true if the two specified vector types are
3113/// compatible.
3114static bool areCompatVectorTypes(const VectorType *LHS,
3115 const VectorType *RHS) {
3116 assert(LHS->isCanonical() && RHS->isCanonical());
3117 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003118 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003119}
3120
Eli Friedman3d815e72008-08-22 00:56:42 +00003121/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003122/// compatible for assignment from RHS to LHS. This handles validation of any
3123/// protocol qualifiers on the LHS or RHS.
3124///
Eli Friedman3d815e72008-08-22 00:56:42 +00003125bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3126 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003127 // Verify that the base decls are compatible: the RHS must be a subclass of
3128 // the LHS.
3129 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3130 return false;
3131
3132 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3133 // protocol qualified at all, then we are good.
3134 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3135 return true;
3136
3137 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3138 // isn't a superset.
3139 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3140 return true; // FIXME: should return false!
3141
3142 // Finally, we must have two protocol-qualified interfaces.
3143 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3144 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003145
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003146 // All LHS protocols must have a presence on the RHS.
3147 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003148
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003149 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3150 LHSPE = LHSP->qual_end();
3151 LHSPI != LHSPE; LHSPI++) {
3152 bool RHSImplementsProtocol = false;
3153
3154 // If the RHS doesn't implement the protocol on the left, the types
3155 // are incompatible.
3156 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3157 RHSPE = RHSP->qual_end();
3158 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3159 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3160 RHSImplementsProtocol = true;
3161 }
3162 // FIXME: For better diagnostics, consider passing back the protocol name.
3163 if (!RHSImplementsProtocol)
3164 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003165 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003166 // The RHS implements all protocols listed on the LHS.
3167 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003168}
3169
Steve Naroff389bf462009-02-12 17:52:19 +00003170bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3171 // get the "pointed to" types
3172 const PointerType *LHSPT = LHS->getAsPointerType();
3173 const PointerType *RHSPT = RHS->getAsPointerType();
3174
3175 if (!LHSPT || !RHSPT)
3176 return false;
3177
3178 QualType lhptee = LHSPT->getPointeeType();
3179 QualType rhptee = RHSPT->getPointeeType();
3180 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
3181 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
3182 // ID acts sort of like void* for ObjC interfaces
3183 if (LHSIface && isObjCIdStructType(rhptee))
3184 return true;
3185 if (RHSIface && isObjCIdStructType(lhptee))
3186 return true;
3187 if (!LHSIface || !RHSIface)
3188 return false;
3189 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
3190 canAssignObjCInterfaces(RHSIface, LHSIface);
3191}
3192
Steve Naroffec0550f2007-10-15 20:41:53 +00003193/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3194/// both shall have the identically qualified version of a compatible type.
3195/// C99 6.2.7p1: Two types have compatible types if their types are the
3196/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003197bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3198 return !mergeTypes(LHS, RHS).isNull();
3199}
3200
3201QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3202 const FunctionType *lbase = lhs->getAsFunctionType();
3203 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003204 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3205 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003206 bool allLTypes = true;
3207 bool allRTypes = true;
3208
3209 // Check return type
3210 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3211 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003212 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3213 allLTypes = false;
3214 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3215 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003216
3217 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003218 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3219 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003220 unsigned lproto_nargs = lproto->getNumArgs();
3221 unsigned rproto_nargs = rproto->getNumArgs();
3222
3223 // Compatible functions must have the same number of arguments
3224 if (lproto_nargs != rproto_nargs)
3225 return QualType();
3226
3227 // Variadic and non-variadic functions aren't compatible
3228 if (lproto->isVariadic() != rproto->isVariadic())
3229 return QualType();
3230
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003231 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3232 return QualType();
3233
Eli Friedman3d815e72008-08-22 00:56:42 +00003234 // Check argument compatibility
3235 llvm::SmallVector<QualType, 10> types;
3236 for (unsigned i = 0; i < lproto_nargs; i++) {
3237 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3238 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3239 QualType argtype = mergeTypes(largtype, rargtype);
3240 if (argtype.isNull()) return QualType();
3241 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003242 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3243 allLTypes = false;
3244 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3245 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003246 }
3247 if (allLTypes) return lhs;
3248 if (allRTypes) return rhs;
3249 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003250 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003251 }
3252
3253 if (lproto) allRTypes = false;
3254 if (rproto) allLTypes = false;
3255
Douglas Gregor72564e72009-02-26 23:50:07 +00003256 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003257 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003258 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003259 if (proto->isVariadic()) return QualType();
3260 // Check that the types are compatible with the types that
3261 // would result from default argument promotions (C99 6.7.5.3p15).
3262 // The only types actually affected are promotable integer
3263 // types and floats, which would be passed as a different
3264 // type depending on whether the prototype is visible.
3265 unsigned proto_nargs = proto->getNumArgs();
3266 for (unsigned i = 0; i < proto_nargs; ++i) {
3267 QualType argTy = proto->getArgType(i);
3268 if (argTy->isPromotableIntegerType() ||
3269 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3270 return QualType();
3271 }
3272
3273 if (allLTypes) return lhs;
3274 if (allRTypes) return rhs;
3275 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003276 proto->getNumArgs(), lproto->isVariadic(),
3277 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003278 }
3279
3280 if (allLTypes) return lhs;
3281 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003282 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003283}
3284
3285QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003286 // C++ [expr]: If an expression initially has the type "reference to T", the
3287 // type is adjusted to "T" prior to any further analysis, the expression
3288 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003289 // expression is an lvalue unless the reference is an rvalue reference and
3290 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003291 // FIXME: C++ shouldn't be going through here! The rules are different
3292 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003293 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3294 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003295 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003296 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003297 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003298 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003299
Eli Friedman3d815e72008-08-22 00:56:42 +00003300 QualType LHSCan = getCanonicalType(LHS),
3301 RHSCan = getCanonicalType(RHS);
3302
3303 // If two types are identical, they are compatible.
3304 if (LHSCan == RHSCan)
3305 return LHS;
3306
3307 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003308 // Note that we handle extended qualifiers later, in the
3309 // case for ExtQualType.
3310 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003311 return QualType();
3312
Eli Friedman852d63b2009-06-01 01:22:52 +00003313 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3314 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003315
Chris Lattner1adb8832008-01-14 05:45:46 +00003316 // We want to consider the two function types to be the same for these
3317 // comparisons, just force one to the other.
3318 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3319 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003320
Eli Friedman07d25872009-06-02 05:28:56 +00003321 // Strip off objc_gc attributes off the top level so they can be merged.
3322 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003323 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003324 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3325 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003326 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003327 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003328 // __strong attribue is redundant if other decl is an objective-c
3329 // object pointer (or decorated with __strong attribute); otherwise
3330 // issue error.
3331 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3332 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3333 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3334 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003335 return QualType();
3336
Eli Friedman07d25872009-06-02 05:28:56 +00003337 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3338 RHS.getCVRQualifiers());
3339 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003340 if (!Result.isNull()) {
3341 if (Result.getObjCGCAttr() == QualType::GCNone)
3342 Result = getObjCGCQualType(Result, GCAttr);
3343 else if (Result.getObjCGCAttr() != GCAttr)
3344 Result = QualType();
3345 }
Eli Friedman07d25872009-06-02 05:28:56 +00003346 return Result;
3347 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003348 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003349 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003350 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3351 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003352 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3353 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003354 // __strong attribue is redundant if other decl is an objective-c
3355 // object pointer (or decorated with __strong attribute); otherwise
3356 // issue error.
3357 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3358 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3359 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3360 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003361 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003362
Eli Friedman07d25872009-06-02 05:28:56 +00003363 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3364 LHS.getCVRQualifiers());
3365 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003366 if (!Result.isNull()) {
3367 if (Result.getObjCGCAttr() == QualType::GCNone)
3368 Result = getObjCGCQualType(Result, GCAttr);
3369 else if (Result.getObjCGCAttr() != GCAttr)
3370 Result = QualType();
3371 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003372 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003373 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003374 }
3375
Eli Friedman4c721d32008-02-12 08:23:06 +00003376 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003377 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3378 LHSClass = Type::ConstantArray;
3379 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3380 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003381
Nate Begeman213541a2008-04-18 23:10:10 +00003382 // Canonicalize ExtVector -> Vector.
3383 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3384 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003385
Chris Lattnerb0489812008-04-07 06:38:24 +00003386 // Consider qualified interfaces and interfaces the same.
3387 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3388 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003389
Chris Lattnera36a61f2008-04-07 05:43:21 +00003390 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003391 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003392 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3393 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003394
Steve Naroffd824c9c2009-04-14 15:11:46 +00003395 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3396 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003397 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003398 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003399 return RHS;
3400
Steve Naroffbc76dd02008-12-10 22:14:21 +00003401 // ID is compatible with all qualified id types.
3402 if (LHS->isObjCQualifiedIdType()) {
3403 if (const PointerType *PT = RHS->getAsPointerType()) {
3404 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003405 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003406 return LHS;
3407 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3408 // Unfortunately, this API is part of Sema (which we don't have access
3409 // to. Need to refactor. The following check is insufficient, since we
3410 // need to make sure the class implements the protocol.
3411 if (pType->isObjCInterfaceType())
3412 return LHS;
3413 }
3414 }
3415 if (RHS->isObjCQualifiedIdType()) {
3416 if (const PointerType *PT = LHS->getAsPointerType()) {
3417 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003418 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003419 return RHS;
3420 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3421 // Unfortunately, this API is part of Sema (which we don't have access
3422 // to. Need to refactor. The following check is insufficient, since we
3423 // need to make sure the class implements the protocol.
3424 if (pType->isObjCInterfaceType())
3425 return RHS;
3426 }
3427 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003428 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3429 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003430 if (const EnumType* ETy = LHS->getAsEnumType()) {
3431 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3432 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003433 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003434 if (const EnumType* ETy = RHS->getAsEnumType()) {
3435 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3436 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003437 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003438
Eli Friedman3d815e72008-08-22 00:56:42 +00003439 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003440 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003441
Steve Naroff4a746782008-01-09 22:43:08 +00003442 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003443 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003444#define TYPE(Class, Base)
3445#define ABSTRACT_TYPE(Class, Base)
3446#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3447#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3448#include "clang/AST/TypeNodes.def"
3449 assert(false && "Non-canonical and dependent types shouldn't get here");
3450 return QualType();
3451
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003452 case Type::LValueReference:
3453 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003454 case Type::MemberPointer:
3455 assert(false && "C++ should never be in mergeTypes");
3456 return QualType();
3457
3458 case Type::IncompleteArray:
3459 case Type::VariableArray:
3460 case Type::FunctionProto:
3461 case Type::ExtVector:
3462 case Type::ObjCQualifiedInterface:
3463 assert(false && "Types are eliminated above");
3464 return QualType();
3465
Chris Lattner1adb8832008-01-14 05:45:46 +00003466 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003467 {
3468 // Merge two pointer types, while trying to preserve typedef info
3469 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3470 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3471 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3472 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003473 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003474 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003475 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003476 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003477 return getPointerType(ResultType);
3478 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003479 case Type::BlockPointer:
3480 {
3481 // Merge two block pointer types, while trying to preserve typedef info
3482 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3483 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3484 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3485 if (ResultType.isNull()) return QualType();
3486 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3487 return LHS;
3488 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3489 return RHS;
3490 return getBlockPointerType(ResultType);
3491 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003492 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003493 {
3494 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3495 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3496 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3497 return QualType();
3498
3499 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3500 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3501 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3502 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003503 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3504 return LHS;
3505 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3506 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003507 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3508 ArrayType::ArraySizeModifier(), 0);
3509 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3510 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003511 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3512 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003513 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3514 return LHS;
3515 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3516 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003517 if (LVAT) {
3518 // FIXME: This isn't correct! But tricky to implement because
3519 // the array's size has to be the size of LHS, but the type
3520 // has to be different.
3521 return LHS;
3522 }
3523 if (RVAT) {
3524 // FIXME: This isn't correct! But tricky to implement because
3525 // the array's size has to be the size of RHS, but the type
3526 // has to be different.
3527 return RHS;
3528 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003529 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3530 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003531 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003532 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003533 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003534 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003535 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003536 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003537 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003538 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3539 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003540 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003541 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003542 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003543 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003544 case Type::Complex:
3545 // Distinct complex types are incompatible.
3546 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003547 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003548 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003549 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3550 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003551 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003552 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003553 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003554 // FIXME: This should be type compatibility, e.g. whether
3555 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003556 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3557 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3558 if (LHSIface && RHSIface &&
3559 canAssignObjCInterfaces(LHSIface, RHSIface))
3560 return LHS;
3561
Eli Friedman3d815e72008-08-22 00:56:42 +00003562 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003563 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003564 case Type::ObjCObjectPointer:
3565 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003566 // Distinct qualified id's are not compatible.
3567 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003568 case Type::FixedWidthInt:
3569 // Distinct fixed-width integers are not compatible.
3570 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003571 case Type::ExtQual:
3572 // FIXME: ExtQual types can be compatible even if they're not
3573 // identical!
3574 return QualType();
3575 // First attempt at an implementation, but I'm not really sure it's
3576 // right...
3577#if 0
3578 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3579 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3580 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3581 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3582 return QualType();
3583 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3584 LHSBase = QualType(LQual->getBaseType(), 0);
3585 RHSBase = QualType(RQual->getBaseType(), 0);
3586 ResultType = mergeTypes(LHSBase, RHSBase);
3587 if (ResultType.isNull()) return QualType();
3588 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3589 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3590 return LHS;
3591 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3592 return RHS;
3593 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3594 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3595 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3596 return ResultType;
3597#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003598
3599 case Type::TemplateSpecialization:
3600 assert(false && "Dependent types have no size");
3601 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003602 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003603
3604 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003605}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003606
Chris Lattner5426bf62008-04-07 07:01:58 +00003607//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003608// Integer Predicates
3609//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003610
Eli Friedmanad74a752008-06-28 06:23:08 +00003611unsigned ASTContext::getIntWidth(QualType T) {
3612 if (T == BoolTy)
3613 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003614 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3615 return FWIT->getWidth();
3616 }
3617 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003618 return (unsigned)getTypeSize(T);
3619}
3620
3621QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3622 assert(T->isSignedIntegerType() && "Unexpected type");
3623 if (const EnumType* ETy = T->getAsEnumType())
3624 T = ETy->getDecl()->getIntegerType();
3625 const BuiltinType* BTy = T->getAsBuiltinType();
3626 assert (BTy && "Unexpected signed integer type");
3627 switch (BTy->getKind()) {
3628 case BuiltinType::Char_S:
3629 case BuiltinType::SChar:
3630 return UnsignedCharTy;
3631 case BuiltinType::Short:
3632 return UnsignedShortTy;
3633 case BuiltinType::Int:
3634 return UnsignedIntTy;
3635 case BuiltinType::Long:
3636 return UnsignedLongTy;
3637 case BuiltinType::LongLong:
3638 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003639 case BuiltinType::Int128:
3640 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003641 default:
3642 assert(0 && "Unexpected signed integer type");
3643 return QualType();
3644 }
3645}
3646
Douglas Gregor2cf26342009-04-09 22:27:44 +00003647ExternalASTSource::~ExternalASTSource() { }
3648
3649void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003650
3651
3652//===----------------------------------------------------------------------===//
3653// Builtin Type Computation
3654//===----------------------------------------------------------------------===//
3655
3656/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3657/// pointer over the consumed characters. This returns the resultant type.
3658static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3659 ASTContext::GetBuiltinTypeError &Error,
3660 bool AllowTypeModifiers = true) {
3661 // Modifiers.
3662 int HowLong = 0;
3663 bool Signed = false, Unsigned = false;
3664
3665 // Read the modifiers first.
3666 bool Done = false;
3667 while (!Done) {
3668 switch (*Str++) {
3669 default: Done = true; --Str; break;
3670 case 'S':
3671 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3672 assert(!Signed && "Can't use 'S' modifier multiple times!");
3673 Signed = true;
3674 break;
3675 case 'U':
3676 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3677 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3678 Unsigned = true;
3679 break;
3680 case 'L':
3681 assert(HowLong <= 2 && "Can't have LLLL modifier");
3682 ++HowLong;
3683 break;
3684 }
3685 }
3686
3687 QualType Type;
3688
3689 // Read the base type.
3690 switch (*Str++) {
3691 default: assert(0 && "Unknown builtin type letter!");
3692 case 'v':
3693 assert(HowLong == 0 && !Signed && !Unsigned &&
3694 "Bad modifiers used with 'v'!");
3695 Type = Context.VoidTy;
3696 break;
3697 case 'f':
3698 assert(HowLong == 0 && !Signed && !Unsigned &&
3699 "Bad modifiers used with 'f'!");
3700 Type = Context.FloatTy;
3701 break;
3702 case 'd':
3703 assert(HowLong < 2 && !Signed && !Unsigned &&
3704 "Bad modifiers used with 'd'!");
3705 if (HowLong)
3706 Type = Context.LongDoubleTy;
3707 else
3708 Type = Context.DoubleTy;
3709 break;
3710 case 's':
3711 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3712 if (Unsigned)
3713 Type = Context.UnsignedShortTy;
3714 else
3715 Type = Context.ShortTy;
3716 break;
3717 case 'i':
3718 if (HowLong == 3)
3719 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3720 else if (HowLong == 2)
3721 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3722 else if (HowLong == 1)
3723 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3724 else
3725 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3726 break;
3727 case 'c':
3728 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3729 if (Signed)
3730 Type = Context.SignedCharTy;
3731 else if (Unsigned)
3732 Type = Context.UnsignedCharTy;
3733 else
3734 Type = Context.CharTy;
3735 break;
3736 case 'b': // boolean
3737 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3738 Type = Context.BoolTy;
3739 break;
3740 case 'z': // size_t.
3741 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3742 Type = Context.getSizeType();
3743 break;
3744 case 'F':
3745 Type = Context.getCFConstantStringType();
3746 break;
3747 case 'a':
3748 Type = Context.getBuiltinVaListType();
3749 assert(!Type.isNull() && "builtin va list type not initialized!");
3750 break;
3751 case 'A':
3752 // This is a "reference" to a va_list; however, what exactly
3753 // this means depends on how va_list is defined. There are two
3754 // different kinds of va_list: ones passed by value, and ones
3755 // passed by reference. An example of a by-value va_list is
3756 // x86, where va_list is a char*. An example of by-ref va_list
3757 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3758 // we want this argument to be a char*&; for x86-64, we want
3759 // it to be a __va_list_tag*.
3760 Type = Context.getBuiltinVaListType();
3761 assert(!Type.isNull() && "builtin va list type not initialized!");
3762 if (Type->isArrayType()) {
3763 Type = Context.getArrayDecayedType(Type);
3764 } else {
3765 Type = Context.getLValueReferenceType(Type);
3766 }
3767 break;
3768 case 'V': {
3769 char *End;
3770
3771 unsigned NumElements = strtoul(Str, &End, 10);
3772 assert(End != Str && "Missing vector size");
3773
3774 Str = End;
3775
3776 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3777 Type = Context.getVectorType(ElementType, NumElements);
3778 break;
3779 }
3780 case 'P': {
3781 IdentifierInfo *II = &Context.Idents.get("FILE");
3782 DeclContext::lookup_result Lookup
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003783 = Context.getTranslationUnitDecl()->lookup(II);
Chris Lattner86df27b2009-06-14 00:45:47 +00003784 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3785 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3786 break;
3787 }
3788 else {
3789 Error = ASTContext::GE_Missing_FILE;
3790 return QualType();
3791 }
3792 }
3793 }
3794
3795 if (!AllowTypeModifiers)
3796 return Type;
3797
3798 Done = false;
3799 while (!Done) {
3800 switch (*Str++) {
3801 default: Done = true; --Str; break;
3802 case '*':
3803 Type = Context.getPointerType(Type);
3804 break;
3805 case '&':
3806 Type = Context.getLValueReferenceType(Type);
3807 break;
3808 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3809 case 'C':
3810 Type = Type.getQualifiedType(QualType::Const);
3811 break;
3812 }
3813 }
3814
3815 return Type;
3816}
3817
3818/// GetBuiltinType - Return the type for the specified builtin.
3819QualType ASTContext::GetBuiltinType(unsigned id,
3820 GetBuiltinTypeError &Error) {
3821 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3822
3823 llvm::SmallVector<QualType, 8> ArgTypes;
3824
3825 Error = GE_None;
3826 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3827 if (Error != GE_None)
3828 return QualType();
3829 while (TypeStr[0] && TypeStr[0] != '.') {
3830 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3831 if (Error != GE_None)
3832 return QualType();
3833
3834 // Do array -> pointer decay. The builtin should use the decayed type.
3835 if (Ty->isArrayType())
3836 Ty = getArrayDecayedType(Ty);
3837
3838 ArgTypes.push_back(Ty);
3839 }
3840
3841 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3842 "'.' should only occur at end of builtin type list!");
3843
3844 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3845 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3846 return getFunctionNoProtoType(ResType);
3847 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3848 TypeStr[0] == '.', 0);
3849}