blob: 9d1e1267e45d0ca9d0f6c85c4fb0a0f233cc0a83 [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),
Douglas Gregorc29f77b2009-07-07 16:35:42 +000039 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
40 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000041 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
42 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000043 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000044 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000045 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000046 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000047}
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049ASTContext::~ASTContext() {
50 // Deallocate all the types.
51 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000052 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000053 Types.pop_back();
54 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000055
Nuno Lopesb74668e2008-12-17 22:30:25 +000056 {
57 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
58 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
59 while (I != E) {
60 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
61 delete R;
62 }
63 }
64
65 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000066 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
67 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000068 while (I != E) {
69 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
70 delete R;
71 }
72 }
73
Douglas Gregorab452ba2009-03-26 23:50:42 +000074 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000075 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
76 NNS = NestedNameSpecifiers.begin(),
77 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000078 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000079 /* Increment in loop */)
80 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000081
82 if (GlobalNestedNameSpecifier)
83 GlobalNestedNameSpecifier->Destroy(*this);
84
Eli Friedmanb26153c2008-05-27 03:08:09 +000085 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
87
Douglas Gregor2cf26342009-04-09 22:27:44 +000088void
89ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
90 ExternalSource.reset(Source.take());
91}
92
Reid Spencer5f016e22007-07-11 17:01:13 +000093void ASTContext::PrintStats() const {
94 fprintf(stderr, "*** AST Context Stats:\n");
95 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000096
Douglas Gregordbe833d2009-05-26 14:40:08 +000097 unsigned counts[] = {
98#define TYPE(Name, Parent) 0,
99#define ABSTRACT_TYPE(Name, Parent)
100#include "clang/AST/TypeNodes.def"
101 0 // Extra
102 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000103
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
105 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000106 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
108
Douglas Gregordbe833d2009-05-26 14:40:08 +0000109 unsigned Idx = 0;
110 unsigned TotalBytes = 0;
111#define TYPE(Name, Parent) \
112 if (counts[Idx]) \
113 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
114 TotalBytes += counts[Idx] * sizeof(Name##Type); \
115 ++Idx;
116#define ABSTRACT_TYPE(Name, Parent)
117#include "clang/AST/TypeNodes.def"
118
119 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000120
121 if (ExternalSource.get()) {
122 fprintf(stderr, "\n");
123 ExternalSource->PrintStats();
124 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000125}
126
127
128void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000129 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000130}
131
Reid Spencer5f016e22007-07-11 17:01:13 +0000132void ASTContext::InitBuiltinTypes() {
133 assert(VoidTy.isNull() && "Context reinitialized?");
134
135 // C99 6.2.5p19.
136 InitBuiltinType(VoidTy, BuiltinType::Void);
137
138 // C99 6.2.5p2.
139 InitBuiltinType(BoolTy, BuiltinType::Bool);
140 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000141 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 InitBuiltinType(CharTy, BuiltinType::Char_S);
143 else
144 InitBuiltinType(CharTy, BuiltinType::Char_U);
145 // C99 6.2.5p4.
146 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
147 InitBuiltinType(ShortTy, BuiltinType::Short);
148 InitBuiltinType(IntTy, BuiltinType::Int);
149 InitBuiltinType(LongTy, BuiltinType::Long);
150 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
151
152 // C99 6.2.5p6.
153 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
154 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
155 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
156 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
157 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
158
159 // C99 6.2.5p10.
160 InitBuiltinType(FloatTy, BuiltinType::Float);
161 InitBuiltinType(DoubleTy, BuiltinType::Double);
162 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000163
Chris Lattner2df9ced2009-04-30 02:43:43 +0000164 // GNU extension, 128-bit integers.
165 InitBuiltinType(Int128Ty, BuiltinType::Int128);
166 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
167
Chris Lattner3a250322009-02-26 23:43:47 +0000168 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
169 InitBuiltinType(WCharTy, BuiltinType::WChar);
170 else // C99
171 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000172
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000173 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
174 InitBuiltinType(Char16Ty, BuiltinType::Char16);
175 else // C99
176 Char16Ty = getFromTargetType(Target.getChar16Type());
177
178 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
179 InitBuiltinType(Char32Ty, BuiltinType::Char32);
180 else // C99
181 Char32Ty = getFromTargetType(Target.getChar32Type());
182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000184 InitBuiltinType(OverloadTy, BuiltinType::Overload);
185
186 // Placeholder type for type-dependent expressions whose type is
187 // completely unknown. No code should ever check a type against
188 // DependentTy and users should never see it; however, it is here to
189 // help diagnose failures to properly check for type-dependent
190 // expressions.
191 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000192
Anders Carlssone89d1592009-06-26 18:41:36 +0000193 // Placeholder type for C++0x auto declarations whose real type has
194 // not yet been deduced.
195 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
196
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 // C99 6.2.5p11.
198 FloatComplexTy = getComplexType(FloatTy);
199 DoubleComplexTy = getComplexType(DoubleTy);
200 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000201
Steve Naroff7e219e42007-10-15 14:41:52 +0000202 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000203
Steve Naroff14108da2009-07-10 23:34:53 +0000204 ObjCIdType = QualType();
205 ObjCClassType = QualType();
206
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000207 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000208
209 // void * type
210 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000211
212 // nullptr type (C++0x 2.14.7)
213 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
Douglas Gregor2e222532009-07-02 17:08:52 +0000216namespace {
217 class BeforeInTranslationUnit
218 : std::binary_function<SourceRange, SourceRange, bool> {
219 SourceManager *SourceMgr;
220
221 public:
222 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
223
224 bool operator()(SourceRange X, SourceRange Y) {
225 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
226 }
227 };
228}
229
230/// \brief Determine whether the given comment is a Doxygen-style comment.
231///
232/// \param Start the start of the comment text.
233///
234/// \param End the end of the comment text.
235///
236/// \param Member whether we want to check whether this is a member comment
237/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
238/// we only return true when we find a non-member comment.
239static bool
240isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
241 bool Member = false) {
242 const char *BufferStart
243 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
244 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
245 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
246
247 if (End - Start < 4)
248 return false;
249
250 assert(Start[0] == '/' && "Not a comment?");
251 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
252 return false;
253 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
254 return false;
255
256 return (Start[3] == '<') == Member;
257}
258
259/// \brief Retrieve the comment associated with the given declaration, if
260/// it has one.
261const char *ASTContext::getCommentForDecl(const Decl *D) {
262 if (!D)
263 return 0;
264
265 // Check whether we have cached a comment string for this declaration
266 // already.
267 llvm::DenseMap<const Decl *, std::string>::iterator Pos
268 = DeclComments.find(D);
269 if (Pos != DeclComments.end())
270 return Pos->second.c_str();
271
272 // If we have an external AST source and have not yet loaded comments from
273 // that source, do so now.
274 if (ExternalSource && !LoadedExternalComments) {
275 std::vector<SourceRange> LoadedComments;
276 ExternalSource->ReadComments(LoadedComments);
277
278 if (!LoadedComments.empty())
279 Comments.insert(Comments.begin(), LoadedComments.begin(),
280 LoadedComments.end());
281
282 LoadedExternalComments = true;
283 }
284
285 // If there are no comments anywhere, we won't find anything.
286 if (Comments.empty())
287 return 0;
288
289 // If the declaration doesn't map directly to a location in a file, we
290 // can't find the comment.
291 SourceLocation DeclStartLoc = D->getLocStart();
292 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
293 return 0;
294
295 // Find the comment that occurs just before this declaration.
296 std::vector<SourceRange>::iterator LastComment
297 = std::lower_bound(Comments.begin(), Comments.end(),
298 SourceRange(DeclStartLoc),
299 BeforeInTranslationUnit(&SourceMgr));
300
301 // Decompose the location for the start of the declaration and find the
302 // beginning of the file buffer.
303 std::pair<FileID, unsigned> DeclStartDecomp
304 = SourceMgr.getDecomposedLoc(DeclStartLoc);
305 const char *FileBufferStart
306 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
307
308 // First check whether we have a comment for a member.
309 if (LastComment != Comments.end() &&
310 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
311 isDoxygenComment(SourceMgr, *LastComment, true)) {
312 std::pair<FileID, unsigned> LastCommentEndDecomp
313 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
314 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
315 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
316 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
317 LastCommentEndDecomp.second)) {
318 // The Doxygen member comment comes after the declaration starts and
319 // is on the same line and in the same file as the declaration. This
320 // is the comment we want.
321 std::string &Result = DeclComments[D];
322 Result.append(FileBufferStart +
323 SourceMgr.getFileOffset(LastComment->getBegin()),
324 FileBufferStart + LastCommentEndDecomp.second + 1);
325 return Result.c_str();
326 }
327 }
328
329 if (LastComment == Comments.begin())
330 return 0;
331 --LastComment;
332
333 // Decompose the end of the comment.
334 std::pair<FileID, unsigned> LastCommentEndDecomp
335 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
336
337 // If the comment and the declaration aren't in the same file, then they
338 // aren't related.
339 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
340 return 0;
341
342 // Check that we actually have a Doxygen comment.
343 if (!isDoxygenComment(SourceMgr, *LastComment))
344 return 0;
345
346 // Compute the starting line for the declaration and for the end of the
347 // comment (this is expensive).
348 unsigned DeclStartLine
349 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
350 unsigned CommentEndLine
351 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
352 LastCommentEndDecomp.second);
353
354 // If the comment does not end on the line prior to the declaration, then
355 // the comment is not associated with the declaration at all.
356 if (CommentEndLine + 1 != DeclStartLine)
357 return 0;
358
359 // We have a comment, but there may be more comments on the previous lines.
360 // Keep looking so long as the comments are still Doxygen comments and are
361 // still adjacent.
362 unsigned ExpectedLine
363 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
364 std::vector<SourceRange>::iterator FirstComment = LastComment;
365 while (FirstComment != Comments.begin()) {
366 // Look at the previous comment
367 --FirstComment;
368 std::pair<FileID, unsigned> Decomp
369 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
370
371 // If this previous comment is in a different file, we're done.
372 if (Decomp.first != DeclStartDecomp.first) {
373 ++FirstComment;
374 break;
375 }
376
377 // If this comment is not a Doxygen comment, we're done.
378 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
379 ++FirstComment;
380 break;
381 }
382
383 // If the line number is not what we expected, we're done.
384 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
385 if (Line != ExpectedLine) {
386 ++FirstComment;
387 break;
388 }
389
390 // Set the next expected line number.
391 ExpectedLine
392 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
393 }
394
395 // The iterator range [FirstComment, LastComment] contains all of the
396 // BCPL comments that, together, are associated with this declaration.
397 // Form a single comment block string for this declaration that concatenates
398 // all of these comments.
399 std::string &Result = DeclComments[D];
400 while (FirstComment != LastComment) {
401 std::pair<FileID, unsigned> DecompStart
402 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
403 std::pair<FileID, unsigned> DecompEnd
404 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
405 Result.append(FileBufferStart + DecompStart.second,
406 FileBufferStart + DecompEnd.second + 1);
407 ++FirstComment;
408 }
409
410 // Append the last comment line.
411 Result.append(FileBufferStart +
412 SourceMgr.getFileOffset(LastComment->getBegin()),
413 FileBufferStart + LastCommentEndDecomp.second + 1);
414 return Result.c_str();
415}
416
Chris Lattner464175b2007-07-18 17:52:12 +0000417//===----------------------------------------------------------------------===//
418// Type Sizing and Analysis
419//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000420
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000421/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
422/// scalar floating point type.
423const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
424 const BuiltinType *BT = T->getAsBuiltinType();
425 assert(BT && "Not a floating point type!");
426 switch (BT->getKind()) {
427 default: assert(0 && "Not a floating point type!");
428 case BuiltinType::Float: return Target.getFloatFormat();
429 case BuiltinType::Double: return Target.getDoubleFormat();
430 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
431 }
432}
433
Chris Lattneraf707ab2009-01-24 21:53:27 +0000434/// getDeclAlign - Return a conservative estimate of the alignment of the
435/// specified decl. Note that bitfields do not have a valid alignment, so
436/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000437unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000438 unsigned Align = Target.getCharWidth();
439
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000440 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000441 Align = std::max(Align, AA->getAlignment());
442
Chris Lattneraf707ab2009-01-24 21:53:27 +0000443 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
444 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000445 if (const ReferenceType* RT = T->getAsReferenceType()) {
446 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000447 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000448 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
449 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000450 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
451 T = cast<ArrayType>(T)->getElementType();
452
453 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
454 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000455 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000456
457 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000458}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000459
Chris Lattnera7674d82007-07-13 22:13:22 +0000460/// getTypeSize - Return the size of the specified type, in bits. This method
461/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000462std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000463ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000464 uint64_t Width=0;
465 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000466 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000467#define TYPE(Class, Base)
468#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000469#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000470#define DEPENDENT_TYPE(Class, Base) case Type::Class:
471#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000472 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000473 break;
474
Chris Lattner692233e2007-07-13 22:27:08 +0000475 case Type::FunctionNoProto:
476 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000477 // GCC extension: alignof(function) = 32 bits
478 Width = 0;
479 Align = 32;
480 break;
481
Douglas Gregor72564e72009-02-26 23:50:07 +0000482 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000483 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000484 Width = 0;
485 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
486 break;
487
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000488 case Type::ConstantArrayWithExpr:
489 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000490 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000491 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000492
Chris Lattner98be4942008-03-05 18:54:05 +0000493 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000494 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000495 Align = EltInfo.second;
496 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000497 }
Nate Begeman213541a2008-04-18 23:10:10 +0000498 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000499 case Type::Vector: {
500 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000501 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000502 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000503 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000504 // If the alignment is not a power of 2, round up to the next power of 2.
505 // This happens for non-power-of-2 length vectors.
506 // FIXME: this should probably be a target property.
507 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000508 break;
509 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000510
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000511 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000512 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000513 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000514 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000515 // GCC extension: alignof(void) = 8 bits.
516 Width = 0;
517 Align = 8;
518 break;
519
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000520 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000521 Width = Target.getBoolWidth();
522 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000523 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000524 case BuiltinType::Char_S:
525 case BuiltinType::Char_U:
526 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000527 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000528 Width = Target.getCharWidth();
529 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000530 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000531 case BuiltinType::WChar:
532 Width = Target.getWCharWidth();
533 Align = Target.getWCharAlign();
534 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000535 case BuiltinType::Char16:
536 Width = Target.getChar16Width();
537 Align = Target.getChar16Align();
538 break;
539 case BuiltinType::Char32:
540 Width = Target.getChar32Width();
541 Align = Target.getChar32Align();
542 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000543 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000544 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000545 Width = Target.getShortWidth();
546 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000547 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000548 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000549 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000550 Width = Target.getIntWidth();
551 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000552 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000553 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000555 Width = Target.getLongWidth();
556 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000557 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000558 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000560 Width = Target.getLongLongWidth();
561 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000562 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000563 case BuiltinType::Int128:
564 case BuiltinType::UInt128:
565 Width = 128;
566 Align = 128; // int128_t is 128-bit aligned on all targets.
567 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000568 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000569 Width = Target.getFloatWidth();
570 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000571 break;
572 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000573 Width = Target.getDoubleWidth();
574 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000575 break;
576 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000577 Width = Target.getLongDoubleWidth();
578 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000579 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000580 case BuiltinType::NullPtr:
581 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
582 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000583 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000584 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000585 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000586 case Type::FixedWidthInt:
587 // FIXME: This isn't precisely correct; the width/alignment should depend
588 // on the available types for the target
589 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000590 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000591 Align = Width;
592 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000593 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000594 // FIXME: Pointers into different addr spaces could have different sizes and
595 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000596 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000597 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000598 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000599 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000600 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000601 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000602 case Type::BlockPointer: {
603 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
604 Width = Target.getPointerWidth(AS);
605 Align = Target.getPointerAlign(AS);
606 break;
607 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000608 case Type::Pointer: {
609 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000610 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000611 Align = Target.getPointerAlign(AS);
612 break;
613 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000614 case Type::LValueReference:
615 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000616 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000617 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000618 // FIXME: This is wrong for struct layout: a reference in a struct has
619 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000620 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000621 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000622 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
623 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
624 // If we ever want to support other ABIs this needs to be abstracted.
625
Sebastian Redlf30208a2009-01-24 21:16:55 +0000626 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000627 std::pair<uint64_t, unsigned> PtrDiffInfo =
628 getTypeInfo(getPointerDiffType());
629 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000630 if (Pointee->isFunctionType())
631 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000632 Align = PtrDiffInfo.second;
633 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000634 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000635 case Type::Complex: {
636 // Complex types have the same alignment as their elements, but twice the
637 // size.
638 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000639 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000641 Align = EltInfo.second;
642 break;
643 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000644 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000645 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000646 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
647 Width = Layout.getSize();
648 Align = Layout.getAlignment();
649 break;
650 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000651 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000652 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000653 const TagType *TT = cast<TagType>(T);
654
655 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000656 Width = 1;
657 Align = 1;
658 break;
659 }
660
Daniel Dunbar1d751182008-11-08 05:48:37 +0000661 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000662 return getTypeInfo(ET->getDecl()->getIntegerType());
663
Daniel Dunbar1d751182008-11-08 05:48:37 +0000664 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000665 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
666 Width = Layout.getSize();
667 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000668 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000669 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000670
Douglas Gregor18857642009-04-30 17:32:17 +0000671 case Type::Typedef: {
672 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000673 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000674 Align = Aligned->getAlignment();
675 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
676 } else
677 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000678 break;
Chris Lattner71763312008-04-06 22:05:18 +0000679 }
Douglas Gregor18857642009-04-30 17:32:17 +0000680
681 case Type::TypeOfExpr:
682 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
683 .getTypePtr());
684
685 case Type::TypeOf:
686 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
687
Anders Carlsson395b4752009-06-24 19:06:50 +0000688 case Type::Decltype:
689 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
690 .getTypePtr());
691
Douglas Gregor18857642009-04-30 17:32:17 +0000692 case Type::QualifiedName:
693 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
694
695 case Type::TemplateSpecialization:
696 assert(getCanonicalType(T) != T &&
697 "Cannot request the size of a dependent type");
698 // FIXME: this is likely to be wrong once we support template
699 // aliases, since a template alias could refer to a typedef that
700 // has an __aligned__ attribute on it.
701 return getTypeInfo(getCanonicalType(T));
702 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000703
Chris Lattner464175b2007-07-18 17:52:12 +0000704 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000705 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000706}
707
Chris Lattner34ebde42009-01-27 18:08:34 +0000708/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
709/// type for the current target in bits. This can be different than the ABI
710/// alignment in cases where it is beneficial for performance to overalign
711/// a data type.
712unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
713 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000714
715 // Double and long long should be naturally aligned if possible.
716 if (const ComplexType* CT = T->getAsComplexType())
717 T = CT->getElementType().getTypePtr();
718 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
719 T->isSpecificBuiltinType(BuiltinType::LongLong))
720 return std::max(ABIAlign, (unsigned)getTypeSize(T));
721
Chris Lattner34ebde42009-01-27 18:08:34 +0000722 return ABIAlign;
723}
724
725
Devang Patel8b277042008-06-04 21:22:16 +0000726/// LayoutField - Field layout.
727void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000728 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000729 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000730 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000731 uint64_t FieldOffset = IsUnion ? 0 : Size;
732 uint64_t FieldSize;
733 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000734
735 // FIXME: Should this override struct packing? Probably we want to
736 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000737 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000738 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000739
740 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
741 // TODO: Need to check this algorithm on other targets!
742 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000743 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000744
745 std::pair<uint64_t, unsigned> FieldInfo =
746 Context.getTypeInfo(FD->getType());
747 uint64_t TypeSize = FieldInfo.first;
748
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000749 // Determine the alignment of this bitfield. The packing
750 // attributes define a maximum and the alignment attribute defines
751 // a minimum.
752 // FIXME: What is the right behavior when the specified alignment
753 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000754 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000755 if (FieldPacking)
756 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000757 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000758 FieldAlign = std::max(FieldAlign, AA->getAlignment());
759
760 // Check if we need to add padding to give the field the correct
761 // alignment.
762 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
763 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
764
765 // Padding members don't affect overall alignment
766 if (!FD->getIdentifier())
767 FieldAlign = 1;
768 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000769 if (FD->getType()->isIncompleteArrayType()) {
770 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000771 // query getTypeInfo about these, so we figure it out here.
772 // Flexible array members don't have any size, but they
773 // have to be aligned appropriately for their element type.
774 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000775 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000776 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000777 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
778 unsigned AS = RT->getPointeeType().getAddressSpace();
779 FieldSize = Context.Target.getPointerWidth(AS);
780 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000781 } else {
782 std::pair<uint64_t, unsigned> FieldInfo =
783 Context.getTypeInfo(FD->getType());
784 FieldSize = FieldInfo.first;
785 FieldAlign = FieldInfo.second;
786 }
787
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000788 // Determine the alignment of this bitfield. The packing
789 // attributes define a maximum and the alignment attribute defines
790 // a minimum. Additionally, the packing alignment must be at least
791 // a byte for non-bitfields.
792 //
793 // FIXME: What is the right behavior when the specified alignment
794 // is smaller than the specified packing?
795 if (FieldPacking)
796 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000797 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000798 FieldAlign = std::max(FieldAlign, AA->getAlignment());
799
800 // Round up the current record size to the field's alignment boundary.
801 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
802 }
803
804 // Place this field at the current location.
805 FieldOffsets[FieldNo] = FieldOffset;
806
807 // Reserve space for this field.
808 if (IsUnion) {
809 Size = std::max(Size, FieldSize);
810 } else {
811 Size = FieldOffset + FieldSize;
812 }
813
Daniel Dunbard6884a02009-05-04 05:16:21 +0000814 // Remember the next available offset.
815 NextOffset = Size;
816
Devang Patel8b277042008-06-04 21:22:16 +0000817 // Remember max struct/class alignment.
818 Alignment = std::max(Alignment, FieldAlign);
819}
820
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000821static void CollectLocalObjCIvars(ASTContext *Ctx,
822 const ObjCInterfaceDecl *OI,
823 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000824 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
825 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000826 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000827 if (!IVDecl->isInvalidDecl())
828 Fields.push_back(cast<FieldDecl>(IVDecl));
829 }
830}
831
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000832void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
833 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
834 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
835 CollectObjCIvars(SuperClass, Fields);
836 CollectLocalObjCIvars(this, OI, Fields);
837}
838
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000839/// ShallowCollectObjCIvars -
840/// Collect all ivars, including those synthesized, in the current class.
841///
842void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
843 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
844 bool CollectSynthesized) {
845 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
846 E = OI->ivar_end(); I != E; ++I) {
847 Ivars.push_back(*I);
848 }
849 if (CollectSynthesized)
850 CollectSynthesizedIvars(OI, Ivars);
851}
852
Fariborz Jahanian98200742009-05-12 18:14:29 +0000853void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
854 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000855 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
856 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000857 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
858 Ivars.push_back(Ivar);
859
860 // Also look into nested protocols.
861 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
862 E = PD->protocol_end(); P != E; ++P)
863 CollectProtocolSynthesizedIvars(*P, Ivars);
864}
865
866/// CollectSynthesizedIvars -
867/// This routine collect synthesized ivars for the designated class.
868///
869void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
870 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000871 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
872 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000873 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
874 Ivars.push_back(Ivar);
875 }
876 // Also look into interface's protocol list for properties declared
877 // in the protocol and whose ivars are synthesized.
878 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
879 PE = OI->protocol_end(); P != PE; ++P) {
880 ObjCProtocolDecl *PD = (*P);
881 CollectProtocolSynthesizedIvars(PD, Ivars);
882 }
883}
884
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000885unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
886 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000887 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
888 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000889 if ((*I)->getPropertyIvarDecl())
890 ++count;
891
892 // Also look into nested protocols.
893 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
894 E = PD->protocol_end(); P != E; ++P)
895 count += CountProtocolSynthesizedIvars(*P);
896 return count;
897}
898
899unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
900{
901 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000902 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
903 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000904 if ((*I)->getPropertyIvarDecl())
905 ++count;
906 }
907 // Also look into interface's protocol list for properties declared
908 // in the protocol and whose ivars are synthesized.
909 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
910 PE = OI->protocol_end(); P != PE; ++P) {
911 ObjCProtocolDecl *PD = (*P);
912 count += CountProtocolSynthesizedIvars(PD);
913 }
914 return count;
915}
916
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000917/// getInterfaceLayoutImpl - Get or compute information about the
918/// layout of the given interface.
919///
920/// \param Impl - If given, also include the layout of the interface's
921/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000922const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000923ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
924 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000925 assert(!D->isForwardDecl() && "Invalid interface decl!");
926
Devang Patel44a3dde2008-06-04 21:54:36 +0000927 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000928 ObjCContainerDecl *Key =
929 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
930 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
931 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000932
Daniel Dunbar453addb2009-05-03 11:16:44 +0000933 unsigned FieldCount = D->ivar_size();
934 // Add in synthesized ivar count if laying out an implementation.
935 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000936 unsigned SynthCount = CountSynthesizedIvars(D);
937 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000938 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000939 // entry. Note we can't cache this because we simply free all
940 // entries later; however we shouldn't look up implementations
941 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000942 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000943 return getObjCLayout(D, 0);
944 }
945
Devang Patel6a5a34c2008-06-06 02:14:01 +0000946 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000947 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000948 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
949 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000950
Daniel Dunbar913af352009-05-07 21:58:26 +0000951 // We start laying out ivars not at the end of the superclass
952 // structure, but at the next byte following the last field.
953 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000954
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000955 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000956 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000957 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000958 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000959 NewEntry->InitializeLayout(FieldCount);
960 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000961
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000962 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000963 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000964 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000965
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000966 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000967 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
968 AA->getAlignment()));
969
970 // Layout each ivar sequentially.
971 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000972 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
973 ShallowCollectObjCIvars(D, Ivars, Impl);
974 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
975 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
976
Devang Patel44a3dde2008-06-04 21:54:36 +0000977 // Finally, round the size of the total struct up to the alignment of the
978 // struct itself.
979 NewEntry->FinalizeLayout();
980 return *NewEntry;
981}
982
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000983const ASTRecordLayout &
984ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
985 return getObjCLayout(D, 0);
986}
987
988const ASTRecordLayout &
989ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
990 return getObjCLayout(D->getClassInterface(), D);
991}
992
Devang Patel88a981b2007-11-01 19:11:01 +0000993/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000994/// specified record (struct/union/class), which indicates its size and field
995/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000996const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000997 D = D->getDefinition(*this);
998 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000999
Chris Lattner464175b2007-07-18 17:52:12 +00001000 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +00001001 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001002 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001003
Devang Patel88a981b2007-11-01 19:11:01 +00001004 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
1005 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
1006 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +00001007 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001008
Douglas Gregore267ff32008-12-11 20:41:00 +00001009 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001010 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001011 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +00001012
Daniel Dunbar3b0db902008-10-16 02:34:03 +00001013 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001014 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +00001015 StructPacking = PA->getAlignment();
1016
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001017 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +00001018 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1019 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001020
Eli Friedman4bd998b2008-05-30 09:31:38 +00001021 // Layout each field, for now, just sequentially, respecting alignment. In
1022 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001023 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001024 for (RecordDecl::field_iterator Field = D->field_begin(),
1025 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001026 Field != FieldEnd; (void)++Field, ++FieldIdx)
1027 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001028
1029 // Finally, round the size of the total struct up to the alignment of the
1030 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001031 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001032 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001033}
1034
Chris Lattnera7674d82007-07-13 22:13:22 +00001035//===----------------------------------------------------------------------===//
1036// Type creation/memoization methods
1037//===----------------------------------------------------------------------===//
1038
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001039QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001040 QualType CanT = getCanonicalType(T);
1041 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001042 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001043
1044 // If we are composing extended qualifiers together, merge together into one
1045 // ExtQualType node.
1046 unsigned CVRQuals = T.getCVRQualifiers();
1047 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1048 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001049
Chris Lattnerb7d25532009-02-18 22:53:11 +00001050 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1051 // If this type already has an address space specified, it cannot get
1052 // another one.
1053 assert(EQT->getAddressSpace() == 0 &&
1054 "Type cannot be in multiple addr spaces!");
1055 GCAttr = EQT->getObjCGCAttr();
1056 TypeNode = EQT->getBaseType();
1057 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001058
Chris Lattnerb7d25532009-02-18 22:53:11 +00001059 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001060 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001061 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001062 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001063 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001064 return QualType(EXTQy, CVRQuals);
1065
Christopher Lambebb97e92008-02-04 02:31:56 +00001066 // If the base type isn't canonical, this won't be a canonical type either,
1067 // so fill in the canonical type field.
1068 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001069 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001070 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001071
Chris Lattnerb7d25532009-02-18 22:53:11 +00001072 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001073 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001074 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001075 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001076 ExtQualType *New =
1077 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001078 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001079 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001080 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001081}
1082
Chris Lattnerb7d25532009-02-18 22:53:11 +00001083QualType ASTContext::getObjCGCQualType(QualType T,
1084 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001085 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001086 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001087 return T;
1088
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001089 if (T->isPointerType()) {
1090 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00001091 if (Pointee->isPointerType() || Pointee->isObjCObjectPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001092 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1093 return getPointerType(ResultType);
1094 }
1095 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001096 // If we are composing extended qualifiers together, merge together into one
1097 // ExtQualType node.
1098 unsigned CVRQuals = T.getCVRQualifiers();
1099 Type *TypeNode = T.getTypePtr();
1100 unsigned AddressSpace = 0;
1101
1102 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1103 // If this type already has an address space specified, it cannot get
1104 // another one.
1105 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1106 "Type cannot be in multiple addr spaces!");
1107 AddressSpace = EQT->getAddressSpace();
1108 TypeNode = EQT->getBaseType();
1109 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001110
1111 // Check if we've already instantiated an gc qual'd type of this type.
1112 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001113 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001114 void *InsertPos = 0;
1115 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001116 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001117
1118 // If the base type isn't canonical, this won't be a canonical type either,
1119 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001120 // FIXME: Isn't this also not canonical if the base type is a array
1121 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001122 QualType Canonical;
1123 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001124 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001125
Chris Lattnerb7d25532009-02-18 22:53:11 +00001126 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001127 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1128 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1129 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001130 ExtQualType *New =
1131 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001132 ExtQualTypes.InsertNode(New, InsertPos);
1133 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001134 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001135}
Chris Lattnera7674d82007-07-13 22:13:22 +00001136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137/// getComplexType - Return the uniqued reference to the type for a complex
1138/// number with the specified element type.
1139QualType ASTContext::getComplexType(QualType T) {
1140 // Unique pointers, to guarantee there is only one pointer of a particular
1141 // structure.
1142 llvm::FoldingSetNodeID ID;
1143 ComplexType::Profile(ID, T);
1144
1145 void *InsertPos = 0;
1146 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1147 return QualType(CT, 0);
1148
1149 // If the pointee type isn't canonical, this won't be a canonical type either,
1150 // so fill in the canonical type field.
1151 QualType Canonical;
1152 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001153 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001154
1155 // Get the new insert position for the node we care about.
1156 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001157 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001158 }
Steve Narofff83820b2009-01-27 22:08:43 +00001159 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 Types.push_back(New);
1161 ComplexTypes.InsertNode(New, InsertPos);
1162 return QualType(New, 0);
1163}
1164
Eli Friedmanf98aba32009-02-13 02:31:07 +00001165QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1166 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1167 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1168 FixedWidthIntType *&Entry = Map[Width];
1169 if (!Entry)
1170 Entry = new FixedWidthIntType(Width, Signed);
1171 return QualType(Entry, 0);
1172}
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174/// getPointerType - Return the uniqued reference to the type for a pointer to
1175/// the specified type.
1176QualType ASTContext::getPointerType(QualType T) {
1177 // Unique pointers, to guarantee there is only one pointer of a particular
1178 // structure.
1179 llvm::FoldingSetNodeID ID;
1180 PointerType::Profile(ID, T);
1181
1182 void *InsertPos = 0;
1183 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1184 return QualType(PT, 0);
1185
1186 // If the pointee type isn't canonical, this won't be a canonical type either,
1187 // so fill in the canonical type field.
1188 QualType Canonical;
1189 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001190 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001191
1192 // Get the new insert position for the node we care about.
1193 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001194 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 }
Steve Narofff83820b2009-01-27 22:08:43 +00001196 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 Types.push_back(New);
1198 PointerTypes.InsertNode(New, InsertPos);
1199 return QualType(New, 0);
1200}
1201
Steve Naroff5618bd42008-08-27 16:04:49 +00001202/// getBlockPointerType - Return the uniqued reference to the type for
1203/// a pointer to the specified block.
1204QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001205 assert(T->isFunctionType() && "block of function types only");
1206 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001207 // structure.
1208 llvm::FoldingSetNodeID ID;
1209 BlockPointerType::Profile(ID, T);
1210
1211 void *InsertPos = 0;
1212 if (BlockPointerType *PT =
1213 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1214 return QualType(PT, 0);
1215
Steve Naroff296e8d52008-08-28 19:20:44 +00001216 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001217 // type either so fill in the canonical type field.
1218 QualType Canonical;
1219 if (!T->isCanonical()) {
1220 Canonical = getBlockPointerType(getCanonicalType(T));
1221
1222 // Get the new insert position for the node we care about.
1223 BlockPointerType *NewIP =
1224 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001225 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001226 }
Steve Narofff83820b2009-01-27 22:08:43 +00001227 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001228 Types.push_back(New);
1229 BlockPointerTypes.InsertNode(New, InsertPos);
1230 return QualType(New, 0);
1231}
1232
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001233/// getLValueReferenceType - Return the uniqued reference to the type for an
1234/// lvalue reference to the specified type.
1235QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 // Unique pointers, to guarantee there is only one pointer of a particular
1237 // structure.
1238 llvm::FoldingSetNodeID ID;
1239 ReferenceType::Profile(ID, T);
1240
1241 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001242 if (LValueReferenceType *RT =
1243 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001245
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // If the referencee type isn't canonical, this won't be a canonical type
1247 // either, so fill in the canonical type field.
1248 QualType Canonical;
1249 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001250 Canonical = getLValueReferenceType(getCanonicalType(T));
1251
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001253 LValueReferenceType *NewIP =
1254 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001255 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 }
1257
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001258 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001260 LValueReferenceTypes.InsertNode(New, InsertPos);
1261 return QualType(New, 0);
1262}
1263
1264/// getRValueReferenceType - Return the uniqued reference to the type for an
1265/// rvalue reference to the specified type.
1266QualType ASTContext::getRValueReferenceType(QualType T) {
1267 // Unique pointers, to guarantee there is only one pointer of a particular
1268 // structure.
1269 llvm::FoldingSetNodeID ID;
1270 ReferenceType::Profile(ID, T);
1271
1272 void *InsertPos = 0;
1273 if (RValueReferenceType *RT =
1274 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1275 return QualType(RT, 0);
1276
1277 // If the referencee type isn't canonical, this won't be a canonical type
1278 // either, so fill in the canonical type field.
1279 QualType Canonical;
1280 if (!T->isCanonical()) {
1281 Canonical = getRValueReferenceType(getCanonicalType(T));
1282
1283 // Get the new insert position for the node we care about.
1284 RValueReferenceType *NewIP =
1285 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1286 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1287 }
1288
1289 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1290 Types.push_back(New);
1291 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 return QualType(New, 0);
1293}
1294
Sebastian Redlf30208a2009-01-24 21:16:55 +00001295/// getMemberPointerType - Return the uniqued reference to the type for a
1296/// member pointer to the specified type, in the specified class.
1297QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1298{
1299 // Unique pointers, to guarantee there is only one pointer of a particular
1300 // structure.
1301 llvm::FoldingSetNodeID ID;
1302 MemberPointerType::Profile(ID, T, Cls);
1303
1304 void *InsertPos = 0;
1305 if (MemberPointerType *PT =
1306 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1307 return QualType(PT, 0);
1308
1309 // If the pointee or class type isn't canonical, this won't be a canonical
1310 // type either, so fill in the canonical type field.
1311 QualType Canonical;
1312 if (!T->isCanonical()) {
1313 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1314
1315 // Get the new insert position for the node we care about.
1316 MemberPointerType *NewIP =
1317 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1318 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1319 }
Steve Narofff83820b2009-01-27 22:08:43 +00001320 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001321 Types.push_back(New);
1322 MemberPointerTypes.InsertNode(New, InsertPos);
1323 return QualType(New, 0);
1324}
1325
Steve Narofffb22d962007-08-30 01:06:46 +00001326/// getConstantArrayType - Return the unique reference to the type for an
1327/// array of the specified element type.
1328QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001329 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001330 ArrayType::ArraySizeModifier ASM,
1331 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001332 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1333 "Constant array of VLAs is illegal!");
1334
Chris Lattner38aeec72009-05-13 04:12:56 +00001335 // Convert the array size into a canonical width matching the pointer size for
1336 // the target.
1337 llvm::APInt ArySize(ArySizeIn);
1338 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001341 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001342
1343 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001344 if (ConstantArrayType *ATP =
1345 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 return QualType(ATP, 0);
1347
1348 // If the element type isn't canonical, this won't be a canonical type either,
1349 // so fill in the canonical type field.
1350 QualType Canonical;
1351 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001352 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001353 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001355 ConstantArrayType *NewIP =
1356 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001357 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 }
1359
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001360 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001361 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001362 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 Types.push_back(New);
1364 return QualType(New, 0);
1365}
1366
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001367/// getConstantArrayWithExprType - Return a reference to the type for
1368/// an array of the specified element type.
1369QualType
1370ASTContext::getConstantArrayWithExprType(QualType EltTy,
1371 const llvm::APInt &ArySizeIn,
1372 Expr *ArySizeExpr,
1373 ArrayType::ArraySizeModifier ASM,
1374 unsigned EltTypeQuals,
1375 SourceRange Brackets) {
1376 // Convert the array size into a canonical width matching the pointer
1377 // size for the target.
1378 llvm::APInt ArySize(ArySizeIn);
1379 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1380
1381 // Compute the canonical ConstantArrayType.
1382 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1383 ArySize, ASM, EltTypeQuals);
1384 // Since we don't unique expressions, it isn't possible to unique VLA's
1385 // that have an expression provided for their size.
1386 ConstantArrayWithExprType *New =
1387 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1388 ArySize, ArySizeExpr,
1389 ASM, EltTypeQuals, Brackets);
1390 Types.push_back(New);
1391 return QualType(New, 0);
1392}
1393
1394/// getConstantArrayWithoutExprType - Return a reference to the type for
1395/// an array of the specified element type.
1396QualType
1397ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1398 const llvm::APInt &ArySizeIn,
1399 ArrayType::ArraySizeModifier ASM,
1400 unsigned EltTypeQuals) {
1401 // Convert the array size into a canonical width matching the pointer
1402 // size for the target.
1403 llvm::APInt ArySize(ArySizeIn);
1404 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1405
1406 // Compute the canonical ConstantArrayType.
1407 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1408 ArySize, ASM, EltTypeQuals);
1409 ConstantArrayWithoutExprType *New =
1410 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1411 ArySize, ASM, EltTypeQuals);
1412 Types.push_back(New);
1413 return QualType(New, 0);
1414}
1415
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001416/// getVariableArrayType - Returns a non-unique reference to the type for a
1417/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001418QualType ASTContext::getVariableArrayType(QualType EltTy,
1419 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001420 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001421 unsigned EltTypeQuals,
1422 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001423 // Since we don't unique expressions, it isn't possible to unique VLA's
1424 // that have an expression provided for their size.
1425
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001426 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001427 new(*this,8)VariableArrayType(EltTy, QualType(),
1428 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001429
1430 VariableArrayTypes.push_back(New);
1431 Types.push_back(New);
1432 return QualType(New, 0);
1433}
1434
Douglas Gregor898574e2008-12-05 23:32:09 +00001435/// getDependentSizedArrayType - Returns a non-unique reference to
1436/// the type for a dependently-sized array of the specified element
1437/// type. FIXME: We will need these to be uniqued, or at least
1438/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001439QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1440 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001441 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001442 unsigned EltTypeQuals,
1443 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001444 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1445 "Size must be type- or value-dependent!");
1446
1447 // Since we don't unique expressions, it isn't possible to unique
1448 // dependently-sized array types.
1449
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001450 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001451 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1452 NumElts, ASM, EltTypeQuals,
1453 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001454
1455 DependentSizedArrayTypes.push_back(New);
1456 Types.push_back(New);
1457 return QualType(New, 0);
1458}
1459
Eli Friedmanc5773c42008-02-15 18:16:39 +00001460QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1461 ArrayType::ArraySizeModifier ASM,
1462 unsigned EltTypeQuals) {
1463 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001464 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001465
1466 void *InsertPos = 0;
1467 if (IncompleteArrayType *ATP =
1468 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1469 return QualType(ATP, 0);
1470
1471 // If the element type isn't canonical, this won't be a canonical type
1472 // either, so fill in the canonical type field.
1473 QualType Canonical;
1474
1475 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001476 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001477 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001478
1479 // Get the new insert position for the node we care about.
1480 IncompleteArrayType *NewIP =
1481 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001482 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001483 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001484
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001485 IncompleteArrayType *New
1486 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1487 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001488
1489 IncompleteArrayTypes.InsertNode(New, InsertPos);
1490 Types.push_back(New);
1491 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001492}
1493
Steve Naroff73322922007-07-18 18:00:27 +00001494/// getVectorType - Return the unique reference to a vector type of
1495/// the specified element type and size. VectorType must be a built-in type.
1496QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 BuiltinType *baseType;
1498
Chris Lattnerf52ab252008-04-06 22:59:24 +00001499 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001500 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001501
1502 // Check if we've already instantiated a vector of this type.
1503 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001504 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 void *InsertPos = 0;
1506 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1507 return QualType(VTP, 0);
1508
1509 // If the element type isn't canonical, this won't be a canonical type either,
1510 // so fill in the canonical type field.
1511 QualType Canonical;
1512 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001513 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001514
1515 // Get the new insert position for the node we care about.
1516 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001517 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 }
Steve Narofff83820b2009-01-27 22:08:43 +00001519 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 VectorTypes.InsertNode(New, InsertPos);
1521 Types.push_back(New);
1522 return QualType(New, 0);
1523}
1524
Nate Begeman213541a2008-04-18 23:10:10 +00001525/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001526/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001527QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001528 BuiltinType *baseType;
1529
Chris Lattnerf52ab252008-04-06 22:59:24 +00001530 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001531 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001532
1533 // Check if we've already instantiated a vector of this type.
1534 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001535 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001536 void *InsertPos = 0;
1537 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1538 return QualType(VTP, 0);
1539
1540 // If the element type isn't canonical, this won't be a canonical type either,
1541 // so fill in the canonical type field.
1542 QualType Canonical;
1543 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001544 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001545
1546 // Get the new insert position for the node we care about.
1547 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001548 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001549 }
Steve Narofff83820b2009-01-27 22:08:43 +00001550 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001551 VectorTypes.InsertNode(New, InsertPos);
1552 Types.push_back(New);
1553 return QualType(New, 0);
1554}
1555
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001556QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1557 Expr *SizeExpr,
1558 SourceLocation AttrLoc) {
1559 DependentSizedExtVectorType *New =
1560 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1561 SizeExpr, AttrLoc);
1562
1563 DependentSizedExtVectorTypes.push_back(New);
1564 Types.push_back(New);
1565 return QualType(New, 0);
1566}
1567
Douglas Gregor72564e72009-02-26 23:50:07 +00001568/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001569///
Douglas Gregor72564e72009-02-26 23:50:07 +00001570QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Unique functions, to guarantee there is only one function of a particular
1572 // structure.
1573 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001574 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575
1576 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001577 if (FunctionNoProtoType *FT =
1578 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 return QualType(FT, 0);
1580
1581 QualType Canonical;
1582 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001583 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001584
1585 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001586 FunctionNoProtoType *NewIP =
1587 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001588 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
1590
Douglas Gregor72564e72009-02-26 23:50:07 +00001591 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001593 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 return QualType(New, 0);
1595}
1596
1597/// getFunctionType - Return a normal function type with a typed argument
1598/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001599QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001600 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001601 unsigned TypeQuals, bool hasExceptionSpec,
1602 bool hasAnyExceptionSpec, unsigned NumExs,
1603 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // Unique functions, to guarantee there is only one function of a particular
1605 // structure.
1606 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001607 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001608 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1609 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001610
1611 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001612 if (FunctionProtoType *FTP =
1613 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001615
1616 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001618 if (hasExceptionSpec)
1619 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1621 if (!ArgArray[i]->isCanonical())
1622 isCanonical = false;
1623
1624 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001625 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 QualType Canonical;
1627 if (!isCanonical) {
1628 llvm::SmallVector<QualType, 16> CanonicalArgs;
1629 CanonicalArgs.reserve(NumArgs);
1630 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001631 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001632
Chris Lattnerf52ab252008-04-06 22:59:24 +00001633 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001634 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001635 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001636
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001638 FunctionProtoType *NewIP =
1639 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001640 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001642
Douglas Gregor72564e72009-02-26 23:50:07 +00001643 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001644 // for two variable size arrays (for parameter and exception types) at the
1645 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001646 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001647 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1648 NumArgs*sizeof(QualType) +
1649 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001650 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001651 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1652 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001654 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 return QualType(FTP, 0);
1656}
1657
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001658/// getTypeDeclType - Return the unique reference to the type for the
1659/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001660QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001661 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001662 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1663
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001664 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001665 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001666 else if (isa<TemplateTypeParmDecl>(Decl)) {
1667 assert(false && "Template type parameter types are always available.");
1668 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001669 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001670
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001671 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001672 if (PrevDecl)
1673 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001674 else
1675 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001676 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001677 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1678 if (PrevDecl)
1679 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001680 else
1681 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001682 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001683 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001684 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001685
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001686 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001687 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001688}
1689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690/// getTypedefType - Return the unique reference to the type for the
1691/// specified typename decl.
1692QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1693 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1694
Chris Lattnerf52ab252008-04-06 22:59:24 +00001695 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001696 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 Types.push_back(Decl->TypeForDecl);
1698 return QualType(Decl->TypeForDecl, 0);
1699}
1700
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001701/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001702/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001703QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001704 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1705
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001706 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1707 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001708 Types.push_back(Decl->TypeForDecl);
1709 return QualType(Decl->TypeForDecl, 0);
1710}
1711
Douglas Gregorfab9d672009-02-05 23:33:38 +00001712/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001713/// parameter or parameter pack with the given depth, index, and (optionally)
1714/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001715QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001716 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001717 IdentifierInfo *Name) {
1718 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001719 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001720 void *InsertPos = 0;
1721 TemplateTypeParmType *TypeParm
1722 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1723
1724 if (TypeParm)
1725 return QualType(TypeParm, 0);
1726
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001727 if (Name) {
1728 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1729 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1730 Name, Canon);
1731 } else
1732 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001733
1734 Types.push_back(TypeParm);
1735 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1736
1737 return QualType(TypeParm, 0);
1738}
1739
Douglas Gregor55f6b142009-02-09 18:46:07 +00001740QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001741ASTContext::getTemplateSpecializationType(TemplateName Template,
1742 const TemplateArgument *Args,
1743 unsigned NumArgs,
1744 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001745 if (!Canon.isNull())
1746 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001747
Douglas Gregor55f6b142009-02-09 18:46:07 +00001748 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001749 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001750
Douglas Gregor55f6b142009-02-09 18:46:07 +00001751 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001752 TemplateSpecializationType *Spec
1753 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001754
1755 if (Spec)
1756 return QualType(Spec, 0);
1757
Douglas Gregor7532dc62009-03-30 22:58:21 +00001758 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001759 sizeof(TemplateArgument) * NumArgs),
1760 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001761 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001762 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001763 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001764
1765 return QualType(Spec, 0);
1766}
1767
Douglas Gregore4e5b052009-03-19 00:18:19 +00001768QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001769ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001770 QualType NamedType) {
1771 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001772 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001773
1774 void *InsertPos = 0;
1775 QualifiedNameType *T
1776 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1777 if (T)
1778 return QualType(T, 0);
1779
Douglas Gregorab452ba2009-03-26 23:50:42 +00001780 T = new (*this) QualifiedNameType(NNS, NamedType,
1781 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001782 Types.push_back(T);
1783 QualifiedNameTypes.InsertNode(T, InsertPos);
1784 return QualType(T, 0);
1785}
1786
Douglas Gregord57959a2009-03-27 23:10:48 +00001787QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1788 const IdentifierInfo *Name,
1789 QualType Canon) {
1790 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1791
1792 if (Canon.isNull()) {
1793 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1794 if (CanonNNS != NNS)
1795 Canon = getTypenameType(CanonNNS, Name);
1796 }
1797
1798 llvm::FoldingSetNodeID ID;
1799 TypenameType::Profile(ID, NNS, Name);
1800
1801 void *InsertPos = 0;
1802 TypenameType *T
1803 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1804 if (T)
1805 return QualType(T, 0);
1806
1807 T = new (*this) TypenameType(NNS, Name, Canon);
1808 Types.push_back(T);
1809 TypenameTypes.InsertNode(T, InsertPos);
1810 return QualType(T, 0);
1811}
1812
Douglas Gregor17343172009-04-01 00:28:59 +00001813QualType
1814ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1815 const TemplateSpecializationType *TemplateId,
1816 QualType Canon) {
1817 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1818
1819 if (Canon.isNull()) {
1820 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1821 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1822 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1823 const TemplateSpecializationType *CanonTemplateId
1824 = CanonType->getAsTemplateSpecializationType();
1825 assert(CanonTemplateId &&
1826 "Canonical type must also be a template specialization type");
1827 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1828 }
1829 }
1830
1831 llvm::FoldingSetNodeID ID;
1832 TypenameType::Profile(ID, NNS, TemplateId);
1833
1834 void *InsertPos = 0;
1835 TypenameType *T
1836 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1837 if (T)
1838 return QualType(T, 0);
1839
1840 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1841 Types.push_back(T);
1842 TypenameTypes.InsertNode(T, InsertPos);
1843 return QualType(T, 0);
1844}
1845
Chris Lattner88cb27a2008-04-07 04:56:42 +00001846/// CmpProtocolNames - Comparison predicate for sorting protocols
1847/// alphabetically.
1848static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1849 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001850 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001851}
1852
1853static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1854 unsigned &NumProtocols) {
1855 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1856
1857 // Sort protocols, keyed by name.
1858 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1859
1860 // Remove duplicates.
1861 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1862 NumProtocols = ProtocolsEnd-Protocols;
1863}
1864
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001865/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1866/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001867QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001868 ObjCProtocolDecl **Protocols,
1869 unsigned NumProtocols) {
Steve Naroff14108da2009-07-10 23:34:53 +00001870 if (InterfaceT.isNull())
1871 InterfaceT = QualType(ObjCObjectPointerType::getIdInterface(), 0);
1872
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001873 // Sort the protocol list alphabetically to canonicalize it.
1874 if (NumProtocols)
1875 SortAndUniqueProtocols(Protocols, NumProtocols);
1876
1877 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001878 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001879
1880 void *InsertPos = 0;
1881 if (ObjCObjectPointerType *QT =
1882 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1883 return QualType(QT, 0);
1884
1885 // No Match;
1886 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001887 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001888
1889 Types.push_back(QType);
1890 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1891 return QualType(QType, 0);
1892}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001893
Chris Lattner065f0d72008-04-07 04:44:08 +00001894/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1895/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001896QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1897 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001898 // Sort the protocol list alphabetically to canonicalize it.
1899 SortAndUniqueProtocols(Protocols, NumProtocols);
1900
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001901 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001902 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001903
1904 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001905 if (ObjCQualifiedInterfaceType *QT =
1906 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001907 return QualType(QT, 0);
1908
1909 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001911 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001912
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001913 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001914 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001915 return QualType(QType, 0);
1916}
1917
Douglas Gregor72564e72009-02-26 23:50:07 +00001918/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1919/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001920/// multiple declarations that refer to "typeof(x)" all contain different
1921/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1922/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001923QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001924 TypeOfExprType *toe;
1925 if (tofExpr->isTypeDependent())
1926 toe = new (*this, 8) TypeOfExprType(tofExpr);
1927 else {
1928 QualType Canonical = getCanonicalType(tofExpr->getType());
1929 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1930 }
Steve Naroff9752f252007-08-01 18:02:17 +00001931 Types.push_back(toe);
1932 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001933}
1934
Steve Naroff9752f252007-08-01 18:02:17 +00001935/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1936/// TypeOfType AST's. The only motivation to unique these nodes would be
1937/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1938/// an issue. This doesn't effect the type checker, since it operates
1939/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001940QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001941 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001942 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001943 Types.push_back(tot);
1944 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001945}
1946
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001947/// getDecltypeForExpr - Given an expr, will return the decltype for that
1948/// expression, according to the rules in C++0x [dcl.type.simple]p4
1949static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001950 if (e->isTypeDependent())
1951 return Context.DependentTy;
1952
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001953 // If e is an id expression or a class member access, decltype(e) is defined
1954 // as the type of the entity named by e.
1955 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1956 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1957 return VD->getType();
1958 }
1959 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1960 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1961 return FD->getType();
1962 }
1963 // If e is a function call or an invocation of an overloaded operator,
1964 // (parentheses around e are ignored), decltype(e) is defined as the
1965 // return type of that function.
1966 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1967 return CE->getCallReturnType();
1968
1969 QualType T = e->getType();
1970
1971 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1972 // defined as T&, otherwise decltype(e) is defined as T.
1973 if (e->isLvalue(Context) == Expr::LV_Valid)
1974 T = Context.getLValueReferenceType(T);
1975
1976 return T;
1977}
1978
Anders Carlsson395b4752009-06-24 19:06:50 +00001979/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1980/// DecltypeType AST's. The only motivation to unique these nodes would be
1981/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1982/// an issue. This doesn't effect the type checker, since it operates
1983/// on canonical type's (which are always unique).
1984QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001985 DecltypeType *dt;
1986 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson563a03b2009-07-10 19:20:26 +00001987 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregordd0257c2009-07-08 00:03:05 +00001988 else {
1989 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00001990 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00001991 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001992 Types.push_back(dt);
1993 return QualType(dt, 0);
1994}
1995
Reid Spencer5f016e22007-07-11 17:01:13 +00001996/// getTagDeclType - Return the unique reference to the type for the
1997/// specified TagDecl (struct/union/class/enum) decl.
1998QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001999 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002000 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002001}
2002
2003/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2004/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2005/// needs to agree with the definition in <stddef.h>.
2006QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002007 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002008}
2009
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002010/// getSignedWCharType - Return the type of "signed wchar_t".
2011/// Used when in C++, as a GCC extension.
2012QualType ASTContext::getSignedWCharType() const {
2013 // FIXME: derive from "Target" ?
2014 return WCharTy;
2015}
2016
2017/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2018/// Used when in C++, as a GCC extension.
2019QualType ASTContext::getUnsignedWCharType() const {
2020 // FIXME: derive from "Target" ?
2021 return UnsignedIntTy;
2022}
2023
Chris Lattner8b9023b2007-07-13 03:05:23 +00002024/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2025/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2026QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002027 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002028}
2029
Chris Lattnere6327742008-04-02 05:18:44 +00002030//===----------------------------------------------------------------------===//
2031// Type Operators
2032//===----------------------------------------------------------------------===//
2033
Chris Lattner77c96472008-04-06 22:41:35 +00002034/// getCanonicalType - Return the canonical (structural) type corresponding to
2035/// the specified potentially non-canonical type. The non-canonical version
2036/// of a type may have many "decorated" versions of types. Decorators can
2037/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2038/// to be free of any of these, allowing two canonical types to be compared
2039/// for exact equality with a simple pointer comparison.
2040QualType ASTContext::getCanonicalType(QualType T) {
2041 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002042
2043 // If the result has type qualifiers, make sure to canonicalize them as well.
2044 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2045 if (TypeQuals == 0) return CanType;
2046
2047 // If the type qualifiers are on an array type, get the canonical type of the
2048 // array with the qualifiers applied to the element type.
2049 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2050 if (!AT)
2051 return CanType.getQualifiedType(TypeQuals);
2052
2053 // Get the canonical version of the element with the extra qualifiers on it.
2054 // This can recursively sink qualifiers through multiple levels of arrays.
2055 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2056 NewEltTy = getCanonicalType(NewEltTy);
2057
2058 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2059 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2060 CAT->getIndexTypeQualifier());
2061 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2062 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2063 IAT->getIndexTypeQualifier());
2064
Douglas Gregor898574e2008-12-05 23:32:09 +00002065 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002066 return getDependentSizedArrayType(NewEltTy,
2067 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002068 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002069 DSAT->getIndexTypeQualifier(),
2070 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002071
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002072 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002073 return getVariableArrayType(NewEltTy,
2074 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002075 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002076 VAT->getIndexTypeQualifier(),
2077 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002078}
2079
Douglas Gregor7da97d02009-05-10 22:57:19 +00002080Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00002081 if (!D)
2082 return 0;
2083
Douglas Gregor7da97d02009-05-10 22:57:19 +00002084 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2085 QualType T = getTagDeclType(Tag);
2086 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2087 ->getDecl());
2088 }
2089
2090 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2091 while (Template->getPreviousDeclaration())
2092 Template = Template->getPreviousDeclaration();
2093 return Template;
2094 }
2095
2096 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2097 while (Function->getPreviousDeclaration())
2098 Function = Function->getPreviousDeclaration();
2099 return const_cast<FunctionDecl *>(Function);
2100 }
2101
Douglas Gregor127102b2009-06-29 20:59:39 +00002102 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2103 while (FunTmpl->getPreviousDeclaration())
2104 FunTmpl = FunTmpl->getPreviousDeclaration();
2105 return FunTmpl;
2106 }
2107
Douglas Gregor7da97d02009-05-10 22:57:19 +00002108 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2109 while (Var->getPreviousDeclaration())
2110 Var = Var->getPreviousDeclaration();
2111 return const_cast<VarDecl *>(Var);
2112 }
2113
2114 return D;
2115}
2116
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002117TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2118 // If this template name refers to a template, the canonical
2119 // template name merely stores the template itself.
2120 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002121 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002122
2123 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2124 assert(DTN && "Non-dependent template names must refer to template decls.");
2125 return DTN->CanonicalTemplateName;
2126}
2127
Douglas Gregord57959a2009-03-27 23:10:48 +00002128NestedNameSpecifier *
2129ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2130 if (!NNS)
2131 return 0;
2132
2133 switch (NNS->getKind()) {
2134 case NestedNameSpecifier::Identifier:
2135 // Canonicalize the prefix but keep the identifier the same.
2136 return NestedNameSpecifier::Create(*this,
2137 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2138 NNS->getAsIdentifier());
2139
2140 case NestedNameSpecifier::Namespace:
2141 // A namespace is canonical; build a nested-name-specifier with
2142 // this namespace and no prefix.
2143 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2144
2145 case NestedNameSpecifier::TypeSpec:
2146 case NestedNameSpecifier::TypeSpecWithTemplate: {
2147 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2148 NestedNameSpecifier *Prefix = 0;
2149
2150 // FIXME: This isn't the right check!
2151 if (T->isDependentType())
2152 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2153
2154 return NestedNameSpecifier::Create(*this, Prefix,
2155 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2156 T.getTypePtr());
2157 }
2158
2159 case NestedNameSpecifier::Global:
2160 // The global specifier is canonical and unique.
2161 return NNS;
2162 }
2163
2164 // Required to silence a GCC warning
2165 return 0;
2166}
2167
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002168
2169const ArrayType *ASTContext::getAsArrayType(QualType T) {
2170 // Handle the non-qualified case efficiently.
2171 if (T.getCVRQualifiers() == 0) {
2172 // Handle the common positive case fast.
2173 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2174 return AT;
2175 }
2176
2177 // Handle the common negative case fast, ignoring CVR qualifiers.
2178 QualType CType = T->getCanonicalTypeInternal();
2179
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002180 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002181 // test.
2182 if (!isa<ArrayType>(CType) &&
2183 !isa<ArrayType>(CType.getUnqualifiedType()))
2184 return 0;
2185
2186 // Apply any CVR qualifiers from the array type to the element type. This
2187 // implements C99 6.7.3p8: "If the specification of an array type includes
2188 // any type qualifiers, the element type is so qualified, not the array type."
2189
2190 // If we get here, we either have type qualifiers on the type, or we have
2191 // sugar such as a typedef in the way. If we have type qualifiers on the type
2192 // we must propagate them down into the elemeng type.
2193 unsigned CVRQuals = T.getCVRQualifiers();
2194 unsigned AddrSpace = 0;
2195 Type *Ty = T.getTypePtr();
2196
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002197 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002198 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002199 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2200 AddrSpace = EXTQT->getAddressSpace();
2201 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002202 } else {
2203 T = Ty->getDesugaredType();
2204 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2205 break;
2206 CVRQuals |= T.getCVRQualifiers();
2207 Ty = T.getTypePtr();
2208 }
2209 }
2210
2211 // If we have a simple case, just return now.
2212 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2213 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2214 return ATy;
2215
2216 // Otherwise, we have an array and we have qualifiers on it. Push the
2217 // qualifiers into the array element type and return a new array type.
2218 // Get the canonical version of the element with the extra qualifiers on it.
2219 // This can recursively sink qualifiers through multiple levels of arrays.
2220 QualType NewEltTy = ATy->getElementType();
2221 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002222 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002223 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2224
2225 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2226 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2227 CAT->getSizeModifier(),
2228 CAT->getIndexTypeQualifier()));
2229 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2230 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2231 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002232 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002233
Douglas Gregor898574e2008-12-05 23:32:09 +00002234 if (const DependentSizedArrayType *DSAT
2235 = dyn_cast<DependentSizedArrayType>(ATy))
2236 return cast<ArrayType>(
2237 getDependentSizedArrayType(NewEltTy,
2238 DSAT->getSizeExpr(),
2239 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002240 DSAT->getIndexTypeQualifier(),
2241 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002242
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002243 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002244 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2245 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002246 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002247 VAT->getIndexTypeQualifier(),
2248 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002249}
2250
2251
Chris Lattnere6327742008-04-02 05:18:44 +00002252/// getArrayDecayedType - Return the properly qualified result of decaying the
2253/// specified array type to a pointer. This operation is non-trivial when
2254/// handling typedefs etc. The canonical type of "T" must be an array type,
2255/// this returns a pointer to a properly qualified element of the array.
2256///
2257/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2258QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002259 // Get the element type with 'getAsArrayType' so that we don't lose any
2260 // typedefs in the element type of the array. This also handles propagation
2261 // of type qualifiers from the array type into the element type if present
2262 // (C99 6.7.3p8).
2263 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2264 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002265
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002266 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002267
2268 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002269 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002270}
2271
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002272QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002273 QualType ElemTy = VAT->getElementType();
2274
2275 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2276 return getBaseElementType(VAT);
2277
2278 return ElemTy;
2279}
2280
Reid Spencer5f016e22007-07-11 17:01:13 +00002281/// getFloatingRank - Return a relative rank for floating point types.
2282/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002283static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002284 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002286
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002287 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002288 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002289 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 case BuiltinType::Float: return FloatRank;
2291 case BuiltinType::Double: return DoubleRank;
2292 case BuiltinType::LongDouble: return LongDoubleRank;
2293 }
2294}
2295
Steve Naroff716c7302007-08-27 01:41:48 +00002296/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2297/// point or a complex type (based on typeDomain/typeSize).
2298/// 'typeDomain' is a real floating point or complex type.
2299/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002300QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2301 QualType Domain) const {
2302 FloatingRank EltRank = getFloatingRank(Size);
2303 if (Domain->isComplexType()) {
2304 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002305 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002306 case FloatRank: return FloatComplexTy;
2307 case DoubleRank: return DoubleComplexTy;
2308 case LongDoubleRank: return LongDoubleComplexTy;
2309 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 }
Chris Lattner1361b112008-04-06 23:58:54 +00002311
2312 assert(Domain->isRealFloatingType() && "Unknown domain!");
2313 switch (EltRank) {
2314 default: assert(0 && "getFloatingRank(): illegal value for rank");
2315 case FloatRank: return FloatTy;
2316 case DoubleRank: return DoubleTy;
2317 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002318 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002319}
2320
Chris Lattner7cfeb082008-04-06 23:55:33 +00002321/// getFloatingTypeOrder - Compare the rank of the two specified floating
2322/// point types, ignoring the domain of the type (i.e. 'double' ==
2323/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2324/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002325int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2326 FloatingRank LHSR = getFloatingRank(LHS);
2327 FloatingRank RHSR = getFloatingRank(RHS);
2328
2329 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002330 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002331 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002332 return 1;
2333 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002334}
2335
Chris Lattnerf52ab252008-04-06 22:59:24 +00002336/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2337/// routine will assert if passed a built-in type that isn't an integer or enum,
2338/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002339unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002340 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002341 if (EnumType* ET = dyn_cast<EnumType>(T))
2342 T = ET->getDecl()->getIntegerType().getTypePtr();
2343
Eli Friedmana3426752009-07-05 23:44:27 +00002344 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2345 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2346
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002347 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2348 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2349
2350 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2351 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2352
Eli Friedmanf98aba32009-02-13 02:31:07 +00002353 // There are two things which impact the integer rank: the width, and
2354 // the ordering of builtins. The builtin ordering is encoded in the
2355 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002356 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002357 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002358
Chris Lattnerf52ab252008-04-06 22:59:24 +00002359 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002360 default: assert(0 && "getIntegerRank(): not a built-in integer");
2361 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002362 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002363 case BuiltinType::Char_S:
2364 case BuiltinType::Char_U:
2365 case BuiltinType::SChar:
2366 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002367 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002368 case BuiltinType::Short:
2369 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002370 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002371 case BuiltinType::Int:
2372 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002373 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002374 case BuiltinType::Long:
2375 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002376 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002377 case BuiltinType::LongLong:
2378 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002379 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002380 case BuiltinType::Int128:
2381 case BuiltinType::UInt128:
2382 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002383 }
2384}
2385
Chris Lattner7cfeb082008-04-06 23:55:33 +00002386/// getIntegerTypeOrder - Returns the highest ranked integer type:
2387/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2388/// LHS < RHS, return -1.
2389int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002390 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2391 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002392 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002393
Chris Lattnerf52ab252008-04-06 22:59:24 +00002394 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2395 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002396
Chris Lattner7cfeb082008-04-06 23:55:33 +00002397 unsigned LHSRank = getIntegerRank(LHSC);
2398 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002399
Chris Lattner7cfeb082008-04-06 23:55:33 +00002400 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2401 if (LHSRank == RHSRank) return 0;
2402 return LHSRank > RHSRank ? 1 : -1;
2403 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002404
Chris Lattner7cfeb082008-04-06 23:55:33 +00002405 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2406 if (LHSUnsigned) {
2407 // If the unsigned [LHS] type is larger, return it.
2408 if (LHSRank >= RHSRank)
2409 return 1;
2410
2411 // If the signed type can represent all values of the unsigned type, it
2412 // wins. Because we are dealing with 2's complement and types that are
2413 // powers of two larger than each other, this is always safe.
2414 return -1;
2415 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002416
Chris Lattner7cfeb082008-04-06 23:55:33 +00002417 // If the unsigned [RHS] type is larger, return it.
2418 if (RHSRank >= LHSRank)
2419 return -1;
2420
2421 // If the signed type can represent all values of the unsigned type, it
2422 // wins. Because we are dealing with 2's complement and types that are
2423 // powers of two larger than each other, this is always safe.
2424 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002425}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002426
2427// getCFConstantStringType - Return the type used for constant CFStrings.
2428QualType ASTContext::getCFConstantStringType() {
2429 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002430 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002431 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002432 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002433 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002434
2435 // const int *isa;
2436 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002437 // int flags;
2438 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002439 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002440 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002441 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002442 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002443
Anders Carlsson71993dd2007-08-17 05:31:46 +00002444 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002445 for (unsigned i = 0; i < 4; ++i) {
2446 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2447 SourceLocation(), 0,
2448 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002449 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002450 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002451 }
2452
2453 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002454 }
2455
2456 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002457}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002458
Douglas Gregor319ac892009-04-23 22:29:11 +00002459void ASTContext::setCFConstantStringType(QualType T) {
2460 const RecordType *Rec = T->getAsRecordType();
2461 assert(Rec && "Invalid CFConstantStringType");
2462 CFConstantStringTypeDecl = Rec->getDecl();
2463}
2464
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002465QualType ASTContext::getObjCFastEnumerationStateType()
2466{
2467 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002468 ObjCFastEnumerationStateTypeDecl =
2469 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2470 &Idents.get("__objcFastEnumerationState"));
2471
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002472 QualType FieldTypes[] = {
2473 UnsignedLongTy,
2474 getPointerType(ObjCIdType),
2475 getPointerType(UnsignedLongTy),
2476 getConstantArrayType(UnsignedLongTy,
2477 llvm::APInt(32, 5), ArrayType::Normal, 0)
2478 };
2479
Douglas Gregor44b43212008-12-11 16:49:14 +00002480 for (size_t i = 0; i < 4; ++i) {
2481 FieldDecl *Field = FieldDecl::Create(*this,
2482 ObjCFastEnumerationStateTypeDecl,
2483 SourceLocation(), 0,
2484 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002485 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002486 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002487 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002488
Douglas Gregor44b43212008-12-11 16:49:14 +00002489 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002490 }
2491
2492 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2493}
2494
Douglas Gregor319ac892009-04-23 22:29:11 +00002495void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2496 const RecordType *Rec = T->getAsRecordType();
2497 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2498 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2499}
2500
Anders Carlssone8c49532007-10-29 06:33:42 +00002501// This returns true if a type has been typedefed to BOOL:
2502// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002503static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002504 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002505 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2506 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002507
2508 return false;
2509}
2510
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002511/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002512/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002513int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002514 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002515
2516 // Make all integer and enum types at least as large as an int
2517 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002518 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002519 // Treat arrays as pointers, since that's how they're passed in.
2520 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002521 sz = getTypeSize(VoidPtrTy);
2522 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002523}
2524
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002525/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002526/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002527void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002528 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002529 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002530 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002532 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002533 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002534 // Compute size of all parameters.
2535 // Start with computing size of a pointer in number of bytes.
2536 // FIXME: There might(should) be a better way of doing this computation!
2537 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002538 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002539 // The first two arguments (self and _cmd) are pointers; account for
2540 // their size.
2541 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002542 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2543 E = Decl->param_end(); PI != E; ++PI) {
2544 QualType PType = (*PI)->getType();
2545 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002547 ParmOffset += sz;
2548 }
2549 S += llvm::utostr(ParmOffset);
2550 S += "@0:";
2551 S += llvm::utostr(PtrSize);
2552
2553 // Argument types.
2554 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002555 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2556 E = Decl->param_end(); PI != E; ++PI) {
2557 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002558 QualType PType = PVDecl->getOriginalType();
2559 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002560 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2561 // Use array's original type only if it has known number of
2562 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002563 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002564 PType = PVDecl->getType();
2565 } else if (PType->isFunctionType())
2566 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002567 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002568 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002569 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002570 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002571 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002572 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002573 }
2574}
2575
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002576/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002577/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002578/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2579/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002580/// Property attributes are stored as a comma-delimited C string. The simple
2581/// attributes readonly and bycopy are encoded as single characters. The
2582/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2583/// encoded as single characters, followed by an identifier. Property types
2584/// are also encoded as a parametrized attribute. The characters used to encode
2585/// these attributes are defined by the following enumeration:
2586/// @code
2587/// enum PropertyAttributes {
2588/// kPropertyReadOnly = 'R', // property is read-only.
2589/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2590/// kPropertyByref = '&', // property is a reference to the value last assigned
2591/// kPropertyDynamic = 'D', // property is dynamic
2592/// kPropertyGetter = 'G', // followed by getter selector name
2593/// kPropertySetter = 'S', // followed by setter selector name
2594/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2595/// kPropertyType = 't' // followed by old-style type encoding.
2596/// kPropertyWeak = 'W' // 'weak' property
2597/// kPropertyStrong = 'P' // property GC'able
2598/// kPropertyNonAtomic = 'N' // property non-atomic
2599/// };
2600/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002601void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2602 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002603 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002604 // Collect information from the property implementation decl(s).
2605 bool Dynamic = false;
2606 ObjCPropertyImplDecl *SynthesizePID = 0;
2607
2608 // FIXME: Duplicated code due to poor abstraction.
2609 if (Container) {
2610 if (const ObjCCategoryImplDecl *CID =
2611 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2612 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002613 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002614 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002615 ObjCPropertyImplDecl *PID = *i;
2616 if (PID->getPropertyDecl() == PD) {
2617 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2618 Dynamic = true;
2619 } else {
2620 SynthesizePID = PID;
2621 }
2622 }
2623 }
2624 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002625 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002626 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002627 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002628 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002629 ObjCPropertyImplDecl *PID = *i;
2630 if (PID->getPropertyDecl() == PD) {
2631 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2632 Dynamic = true;
2633 } else {
2634 SynthesizePID = PID;
2635 }
2636 }
2637 }
2638 }
2639 }
2640
2641 // FIXME: This is not very efficient.
2642 S = "T";
2643
2644 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002645 // GCC has some special rules regarding encoding of properties which
2646 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002647 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002648 true /* outermost type */,
2649 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002650
2651 if (PD->isReadOnly()) {
2652 S += ",R";
2653 } else {
2654 switch (PD->getSetterKind()) {
2655 case ObjCPropertyDecl::Assign: break;
2656 case ObjCPropertyDecl::Copy: S += ",C"; break;
2657 case ObjCPropertyDecl::Retain: S += ",&"; break;
2658 }
2659 }
2660
2661 // It really isn't clear at all what this means, since properties
2662 // are "dynamic by default".
2663 if (Dynamic)
2664 S += ",D";
2665
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002666 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2667 S += ",N";
2668
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002669 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2670 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002671 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002672 }
2673
2674 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2675 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002676 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002677 }
2678
2679 if (SynthesizePID) {
2680 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2681 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002682 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002683 }
2684
2685 // FIXME: OBJCGC: weak & strong
2686}
2687
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002688/// getLegacyIntegralTypeEncoding -
2689/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002690/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002691/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2692///
2693void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2694 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2695 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002696 if (BT->getKind() == BuiltinType::ULong &&
2697 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002698 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002699 else
2700 if (BT->getKind() == BuiltinType::Long &&
2701 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002702 PointeeTy = IntTy;
2703 }
2704 }
2705}
2706
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002707void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002708 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002709 // We follow the behavior of gcc, expanding structures which are
2710 // directly pointed to, and expanding embedded structures. Note that
2711 // these rules are sufficient to prevent recursive encoding of the
2712 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002713 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2714 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002715}
2716
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002717static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002718 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002719 const Expr *E = FD->getBitWidth();
2720 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2721 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002722 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002723 S += 'b';
2724 S += llvm::utostr(N);
2725}
2726
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002727void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2728 bool ExpandPointedToStructures,
2729 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002730 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002731 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002732 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002733 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002734 if (FD && FD->isBitField())
2735 return EncodeBitField(this, S, FD);
2736 char encoding;
2737 switch (BT->getKind()) {
2738 default: assert(0 && "Unhandled builtin type kind");
2739 case BuiltinType::Void: encoding = 'v'; break;
2740 case BuiltinType::Bool: encoding = 'B'; break;
2741 case BuiltinType::Char_U:
2742 case BuiltinType::UChar: encoding = 'C'; break;
2743 case BuiltinType::UShort: encoding = 'S'; break;
2744 case BuiltinType::UInt: encoding = 'I'; break;
2745 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002746 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002747 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002748 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002749 case BuiltinType::UInt128: encoding = 'T'; break;
2750 case BuiltinType::ULongLong: encoding = 'Q'; break;
2751 case BuiltinType::Char_S:
2752 case BuiltinType::SChar: encoding = 'c'; break;
2753 case BuiltinType::Short: encoding = 's'; break;
2754 case BuiltinType::Int: encoding = 'i'; break;
2755 case BuiltinType::Long:
2756 encoding =
2757 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2758 break;
2759 case BuiltinType::LongLong: encoding = 'q'; break;
2760 case BuiltinType::Int128: encoding = 't'; break;
2761 case BuiltinType::Float: encoding = 'f'; break;
2762 case BuiltinType::Double: encoding = 'd'; break;
2763 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002764 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002765
2766 S += encoding;
2767 return;
2768 }
2769
2770 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002771 S += 'j';
2772 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2773 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002774 return;
2775 }
2776
2777 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002778 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002779 bool isReadOnly = false;
2780 // For historical/compatibility reasons, the read-only qualifier of the
2781 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2782 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2783 // Also, do not emit the 'r' for anything but the outermost type!
2784 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2785 if (OutermostType && T.isConstQualified()) {
2786 isReadOnly = true;
2787 S += 'r';
2788 }
2789 }
2790 else if (OutermostType) {
2791 QualType P = PointeeTy;
2792 while (P->getAsPointerType())
2793 P = P->getAsPointerType()->getPointeeType();
2794 if (P.isConstQualified()) {
2795 isReadOnly = true;
2796 S += 'r';
2797 }
2798 }
2799 if (isReadOnly) {
2800 // Another legacy compatibility encoding. Some ObjC qualifier and type
2801 // combinations need to be rearranged.
2802 // Rewrite "in const" from "nr" to "rn"
2803 const char * s = S.c_str();
2804 int len = S.length();
2805 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2806 std::string replace = "rn";
2807 S.replace(S.end()-2, S.end(), replace);
2808 }
2809 }
Steve Naroff14108da2009-07-10 23:34:53 +00002810 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002811 S += ':';
2812 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002813 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002814
2815 if (PointeeTy->isCharType()) {
2816 // char pointer types should be encoded as '*' unless it is a
2817 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002818 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002819 S += '*';
2820 return;
2821 }
2822 }
2823
2824 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002825 getLegacyIntegralTypeEncoding(PointeeTy);
2826
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002827 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002828 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002829 return;
2830 }
2831
2832 if (const ArrayType *AT =
2833 // Ignore type qualifiers etc.
2834 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002835 if (isa<IncompleteArrayType>(AT)) {
2836 // Incomplete arrays are encoded as a pointer to the array element.
2837 S += '^';
2838
2839 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2840 false, ExpandStructures, FD);
2841 } else {
2842 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002843
Anders Carlsson559a8332009-02-22 01:38:57 +00002844 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2845 S += llvm::utostr(CAT->getSize().getZExtValue());
2846 else {
2847 //Variable length arrays are encoded as a regular array with 0 elements.
2848 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2849 S += '0';
2850 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002851
Anders Carlsson559a8332009-02-22 01:38:57 +00002852 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2853 false, ExpandStructures, FD);
2854 S += ']';
2855 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002856 return;
2857 }
2858
2859 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002860 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002861 return;
2862 }
2863
2864 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002865 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002866 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002867 // Anonymous structures print as '?'
2868 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2869 S += II->getName();
2870 } else {
2871 S += '?';
2872 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002873 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002874 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002875 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2876 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002877 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002878 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002879 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002880 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002881 S += '"';
2882 }
2883
2884 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002885 if (Field->isBitField()) {
2886 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2887 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002888 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002889 QualType qt = Field->getType();
2890 getLegacyIntegralTypeEncoding(qt);
2891 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002892 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002893 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002894 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002895 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002896 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002897 return;
2898 }
2899
2900 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002901 if (FD && FD->isBitField())
2902 EncodeBitField(this, S, FD);
2903 else
2904 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002905 return;
2906 }
2907
2908 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002909 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002910 return;
2911 }
2912
2913 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002914 // @encode(class_name)
2915 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2916 S += '{';
2917 const IdentifierInfo *II = OI->getIdentifier();
2918 S += II->getName();
2919 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002920 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002921 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002922 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002923 if (RecFields[i]->isBitField())
2924 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2925 RecFields[i]);
2926 else
2927 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2928 FD);
2929 }
2930 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002931 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002932 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002933
2934 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002935 if (OPT->isObjCIdType()) {
2936 S += '@';
2937 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002938 }
2939
2940 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002941 S += '#';
2942 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002943 }
2944
2945 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002946 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2947 ExpandPointedToStructures,
2948 ExpandStructures, FD);
2949 if (FD || EncodingProperty) {
2950 // Note that we do extended encoding of protocol qualifer list
2951 // Only when doing ivar or property encoding.
2952 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2953 S += '"';
2954 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2955 E = QIDT->qual_end(); I != E; ++I) {
2956 S += '<';
2957 S += (*I)->getNameAsString();
2958 S += '>';
2959 }
2960 S += '"';
2961 }
2962 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002963 }
2964
2965 QualType PointeeTy = OPT->getPointeeType();
2966 if (!EncodingProperty &&
2967 isa<TypedefType>(PointeeTy.getTypePtr())) {
2968 // Another historical/compatibility reason.
2969 // We encode the underlying type which comes out as
2970 // {...};
2971 S += '^';
2972 getObjCEncodingForTypeImpl(PointeeTy, S,
2973 false, ExpandPointedToStructures,
2974 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00002975 return;
2976 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002977
2978 S += '@';
2979 if (FD || EncodingProperty) {
2980 const ObjCInterfaceType *OIT = OPT->getInterfaceType();
2981 ObjCInterfaceDecl *OI = OIT->getDecl();
2982 S += '"';
2983 S += OI->getNameAsCString();
2984 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2985 E = OIT->qual_end(); I != E; ++I) {
2986 S += '<';
2987 S += (*I)->getNameAsString();
2988 S += '>';
2989 }
2990 S += '"';
2991 }
2992 return;
2993 }
2994
2995 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002996}
2997
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002998void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002999 std::string& S) const {
3000 if (QT & Decl::OBJC_TQ_In)
3001 S += 'n';
3002 if (QT & Decl::OBJC_TQ_Inout)
3003 S += 'N';
3004 if (QT & Decl::OBJC_TQ_Out)
3005 S += 'o';
3006 if (QT & Decl::OBJC_TQ_Bycopy)
3007 S += 'O';
3008 if (QT & Decl::OBJC_TQ_Byref)
3009 S += 'R';
3010 if (QT & Decl::OBJC_TQ_Oneway)
3011 S += 'V';
3012}
3013
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003014void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003015 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3016
3017 BuiltinVaListType = T;
3018}
3019
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003020void ASTContext::setObjCIdType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003021 ObjCIdType = T;
Douglas Gregor319ac892009-04-23 22:29:11 +00003022 const TypedefType *TT = T->getAsTypedefType();
Steve Naroff14108da2009-07-10 23:34:53 +00003023 assert(TT && "missing 'id' typedef");
3024 const ObjCObjectPointerType *OPT =
3025 TT->getDecl()->getUnderlyingType()->getAsObjCObjectPointerType();
3026 assert(OPT && "missing 'id' type");
3027 ObjCObjectPointerType::setIdInterface(OPT->getPointeeType());
Steve Naroff7e219e42007-10-15 14:41:52 +00003028}
3029
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003030void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003031 ObjCSelType = T;
3032
3033 const TypedefType *TT = T->getAsTypedefType();
3034 if (!TT)
3035 return;
3036 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003037
3038 // typedef struct objc_selector *SEL;
3039 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003040 if (!ptr)
3041 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003042 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003043 if (!rec)
3044 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003045 SelStructType = rec;
3046}
3047
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003048void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003049 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003050}
3051
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003052void ASTContext::setObjCClassType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003053 ObjCClassType = T;
Douglas Gregor319ac892009-04-23 22:29:11 +00003054 const TypedefType *TT = T->getAsTypedefType();
Steve Naroff14108da2009-07-10 23:34:53 +00003055 assert(TT && "missing 'Class' typedef");
3056 const ObjCObjectPointerType *OPT =
3057 TT->getDecl()->getUnderlyingType()->getAsObjCObjectPointerType();
3058 assert(OPT && "missing 'Class' type");
3059 ObjCObjectPointerType::setClassInterface(OPT->getPointeeType());
Anders Carlsson8baaca52007-10-31 02:53:19 +00003060}
3061
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003062void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3063 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003064 "'NSConstantString' type already set!");
3065
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003066 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003067}
3068
Douglas Gregor7532dc62009-03-30 22:58:21 +00003069/// \brief Retrieve the template name that represents a qualified
3070/// template name such as \c std::vector.
3071TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3072 bool TemplateKeyword,
3073 TemplateDecl *Template) {
3074 llvm::FoldingSetNodeID ID;
3075 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3076
3077 void *InsertPos = 0;
3078 QualifiedTemplateName *QTN =
3079 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3080 if (!QTN) {
3081 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3082 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3083 }
3084
3085 return TemplateName(QTN);
3086}
3087
3088/// \brief Retrieve the template name that represents a dependent
3089/// template name such as \c MetaFun::template apply.
3090TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3091 const IdentifierInfo *Name) {
3092 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3093
3094 llvm::FoldingSetNodeID ID;
3095 DependentTemplateName::Profile(ID, NNS, Name);
3096
3097 void *InsertPos = 0;
3098 DependentTemplateName *QTN =
3099 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3100
3101 if (QTN)
3102 return TemplateName(QTN);
3103
3104 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3105 if (CanonNNS == NNS) {
3106 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3107 } else {
3108 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3109 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3110 }
3111
3112 DependentTemplateNames.InsertNode(QTN, InsertPos);
3113 return TemplateName(QTN);
3114}
3115
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003116/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003117/// TargetInfo, produce the corresponding type. The unsigned @p Type
3118/// is actually a value of type @c TargetInfo::IntType.
3119QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003120 switch (Type) {
3121 case TargetInfo::NoInt: return QualType();
3122 case TargetInfo::SignedShort: return ShortTy;
3123 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3124 case TargetInfo::SignedInt: return IntTy;
3125 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3126 case TargetInfo::SignedLong: return LongTy;
3127 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3128 case TargetInfo::SignedLongLong: return LongLongTy;
3129 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3130 }
3131
3132 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003133 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003134}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003135
3136//===----------------------------------------------------------------------===//
3137// Type Predicates.
3138//===----------------------------------------------------------------------===//
3139
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003140/// isObjCNSObjectType - Return true if this is an NSObject object using
3141/// NSObject attribute on a c-style pointer type.
3142/// FIXME - Make it work directly on types.
3143///
3144bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3145 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3146 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003147 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003148 return true;
3149 }
3150 return false;
3151}
3152
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003153/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3154/// to an object type. This includes "id" and "Class" (two 'special' pointers
3155/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3156/// ID type).
3157bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroff14108da2009-07-10 23:34:53 +00003158 if (Ty->isObjCObjectPointerType())
3159 return true;
Steve Naroffd4617772009-02-23 18:36:16 +00003160 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003161 return true;
3162
Steve Naroff6ae98502008-10-21 18:24:04 +00003163 // Blocks are objects.
3164 if (Ty->isBlockPointerType())
3165 return true;
3166
3167 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00003168 const PointerType *PT = Ty->getAsPointerType();
3169 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003170 return false;
3171
Chris Lattner16ede0e2009-04-12 23:51:02 +00003172 // If this a pointer to an interface (e.g. NSString*), it is ok.
3173 if (PT->getPointeeType()->isObjCInterfaceType() ||
3174 // If is has NSObject attribute, OK as well.
3175 isObjCNSObjectType(Ty))
3176 return true;
3177
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003178 // Check to see if this is 'id' or 'Class', both of which are typedefs for
3179 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00003180 // underlying type. Iteratively strip off typedefs so that we can handle
3181 // typedefs of typedefs.
3182 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3183 if (Ty.getUnqualifiedType() == getObjCIdType() ||
3184 Ty.getUnqualifiedType() == getObjCClassType())
3185 return true;
3186
3187 Ty = TDT->getDecl()->getUnderlyingType();
3188 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003189
Chris Lattner16ede0e2009-04-12 23:51:02 +00003190 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003191}
3192
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003193/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3194/// garbage collection attribute.
3195///
3196QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003197 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003198 if (getLangOptions().ObjC1 &&
3199 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003200 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003201 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003202 // (or pointers to them) be treated as though they were declared
3203 // as __strong.
3204 if (GCAttrs == QualType::GCNone) {
3205 if (isObjCObjectPointerType(Ty))
3206 GCAttrs = QualType::Strong;
3207 else if (Ty->isPointerType())
3208 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3209 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003210 // Non-pointers have none gc'able attribute regardless of the attribute
3211 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003212 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003213 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003214 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003215 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003216}
3217
Chris Lattner6ac46a42008-04-07 06:51:04 +00003218//===----------------------------------------------------------------------===//
3219// Type Compatibility Testing
3220//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003221
Chris Lattner6ac46a42008-04-07 06:51:04 +00003222/// areCompatVectorTypes - Return true if the two specified vector types are
3223/// compatible.
3224static bool areCompatVectorTypes(const VectorType *LHS,
3225 const VectorType *RHS) {
3226 assert(LHS->isCanonical() && RHS->isCanonical());
3227 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003228 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003229}
3230
Eli Friedman3d815e72008-08-22 00:56:42 +00003231/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003232/// compatible for assignment from RHS to LHS. This handles validation of any
3233/// protocol qualifiers on the LHS or RHS.
3234///
Steve Naroff14108da2009-07-10 23:34:53 +00003235/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3236bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3237 const ObjCObjectPointerType *RHSOPT) {
3238 // If either interface represents the built-in 'id' or 'Class' types,
3239 // then return true (no need to call canAssignObjCInterfaces()).
3240 if (LHSOPT->isObjCIdType() || RHSOPT->isObjCIdType() ||
3241 LHSOPT->isObjCClassType() || RHSOPT->isObjCClassType())
3242 return true;
3243
3244 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3245 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3246 if (!LHS || !RHS)
3247 return false;
3248 return canAssignObjCInterfaces(LHS, RHS);
3249}
3250
Eli Friedman3d815e72008-08-22 00:56:42 +00003251bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3252 const ObjCInterfaceType *RHS) {
Steve Naroff14108da2009-07-10 23:34:53 +00003253 // If either interface represents the built-in 'id' or 'Class' types,
3254 // then return true.
3255 if (LHS->isObjCIdInterface() || RHS->isObjCIdInterface() ||
3256 LHS->isObjCClassInterface() || RHS->isObjCClassInterface())
3257 return true;
3258
Chris Lattner6ac46a42008-04-07 06:51:04 +00003259 // Verify that the base decls are compatible: the RHS must be a subclass of
3260 // the LHS.
3261 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3262 return false;
3263
3264 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3265 // protocol qualified at all, then we are good.
3266 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3267 return true;
3268
3269 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3270 // isn't a superset.
3271 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3272 return true; // FIXME: should return false!
3273
3274 // Finally, we must have two protocol-qualified interfaces.
3275 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3276 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003277
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003278 // All LHS protocols must have a presence on the RHS.
3279 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003280
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003281 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3282 LHSPE = LHSP->qual_end();
3283 LHSPI != LHSPE; LHSPI++) {
3284 bool RHSImplementsProtocol = false;
3285
3286 // If the RHS doesn't implement the protocol on the left, the types
3287 // are incompatible.
3288 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3289 RHSPE = RHSP->qual_end();
3290 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3291 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3292 RHSImplementsProtocol = true;
3293 }
3294 // FIXME: For better diagnostics, consider passing back the protocol name.
3295 if (!RHSImplementsProtocol)
3296 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003297 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003298 // The RHS implements all protocols listed on the LHS.
3299 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003300}
3301
Steve Naroff389bf462009-02-12 17:52:19 +00003302bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3303 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003304 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3305 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003306
Steve Naroff14108da2009-07-10 23:34:53 +00003307 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003308 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003309
3310 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3311 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003312}
3313
Steve Naroffec0550f2007-10-15 20:41:53 +00003314/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3315/// both shall have the identically qualified version of a compatible type.
3316/// C99 6.2.7p1: Two types have compatible types if their types are the
3317/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003318bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3319 return !mergeTypes(LHS, RHS).isNull();
3320}
3321
3322QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3323 const FunctionType *lbase = lhs->getAsFunctionType();
3324 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003325 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3326 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003327 bool allLTypes = true;
3328 bool allRTypes = true;
3329
3330 // Check return type
3331 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3332 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003333 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3334 allLTypes = false;
3335 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3336 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003337
3338 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003339 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3340 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003341 unsigned lproto_nargs = lproto->getNumArgs();
3342 unsigned rproto_nargs = rproto->getNumArgs();
3343
3344 // Compatible functions must have the same number of arguments
3345 if (lproto_nargs != rproto_nargs)
3346 return QualType();
3347
3348 // Variadic and non-variadic functions aren't compatible
3349 if (lproto->isVariadic() != rproto->isVariadic())
3350 return QualType();
3351
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003352 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3353 return QualType();
3354
Eli Friedman3d815e72008-08-22 00:56:42 +00003355 // Check argument compatibility
3356 llvm::SmallVector<QualType, 10> types;
3357 for (unsigned i = 0; i < lproto_nargs; i++) {
3358 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3359 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3360 QualType argtype = mergeTypes(largtype, rargtype);
3361 if (argtype.isNull()) return QualType();
3362 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003363 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3364 allLTypes = false;
3365 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3366 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003367 }
3368 if (allLTypes) return lhs;
3369 if (allRTypes) return rhs;
3370 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003371 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003372 }
3373
3374 if (lproto) allRTypes = false;
3375 if (rproto) allLTypes = false;
3376
Douglas Gregor72564e72009-02-26 23:50:07 +00003377 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003378 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003379 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003380 if (proto->isVariadic()) return QualType();
3381 // Check that the types are compatible with the types that
3382 // would result from default argument promotions (C99 6.7.5.3p15).
3383 // The only types actually affected are promotable integer
3384 // types and floats, which would be passed as a different
3385 // type depending on whether the prototype is visible.
3386 unsigned proto_nargs = proto->getNumArgs();
3387 for (unsigned i = 0; i < proto_nargs; ++i) {
3388 QualType argTy = proto->getArgType(i);
3389 if (argTy->isPromotableIntegerType() ||
3390 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3391 return QualType();
3392 }
3393
3394 if (allLTypes) return lhs;
3395 if (allRTypes) return rhs;
3396 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003397 proto->getNumArgs(), lproto->isVariadic(),
3398 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003399 }
3400
3401 if (allLTypes) return lhs;
3402 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003403 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003404}
3405
3406QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003407 // C++ [expr]: If an expression initially has the type "reference to T", the
3408 // type is adjusted to "T" prior to any further analysis, the expression
3409 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003410 // expression is an lvalue unless the reference is an rvalue reference and
3411 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003412 // FIXME: C++ shouldn't be going through here! The rules are different
3413 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003414 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3415 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003416 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003417 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003418 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003419 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003420
Eli Friedman3d815e72008-08-22 00:56:42 +00003421 QualType LHSCan = getCanonicalType(LHS),
3422 RHSCan = getCanonicalType(RHS);
3423
3424 // If two types are identical, they are compatible.
3425 if (LHSCan == RHSCan)
3426 return LHS;
3427
3428 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003429 // Note that we handle extended qualifiers later, in the
3430 // case for ExtQualType.
3431 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003432 return QualType();
3433
Eli Friedman852d63b2009-06-01 01:22:52 +00003434 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3435 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003436
Chris Lattner1adb8832008-01-14 05:45:46 +00003437 // We want to consider the two function types to be the same for these
3438 // comparisons, just force one to the other.
3439 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3440 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003441
Eli Friedman07d25872009-06-02 05:28:56 +00003442 // Strip off objc_gc attributes off the top level so they can be merged.
3443 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003444 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003445 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3446 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003447 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003448 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003449 // __strong attribue is redundant if other decl is an objective-c
3450 // object pointer (or decorated with __strong attribute); otherwise
3451 // issue error.
3452 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3453 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003454 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003455 return QualType();
3456
Eli Friedman07d25872009-06-02 05:28:56 +00003457 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3458 RHS.getCVRQualifiers());
3459 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003460 if (!Result.isNull()) {
3461 if (Result.getObjCGCAttr() == QualType::GCNone)
3462 Result = getObjCGCQualType(Result, GCAttr);
3463 else if (Result.getObjCGCAttr() != GCAttr)
3464 Result = QualType();
3465 }
Eli Friedman07d25872009-06-02 05:28:56 +00003466 return Result;
3467 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003468 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003469 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003470 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3471 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003472 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3473 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003474 // __strong attribue is redundant if other decl is an objective-c
3475 // object pointer (or decorated with __strong attribute); otherwise
3476 // issue error.
3477 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3478 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003479 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003480 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003481
Eli Friedman07d25872009-06-02 05:28:56 +00003482 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3483 LHS.getCVRQualifiers());
3484 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003485 if (!Result.isNull()) {
3486 if (Result.getObjCGCAttr() == QualType::GCNone)
3487 Result = getObjCGCQualType(Result, GCAttr);
3488 else if (Result.getObjCGCAttr() != GCAttr)
3489 Result = QualType();
3490 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003491 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003492 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003493 }
3494
Eli Friedman4c721d32008-02-12 08:23:06 +00003495 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003496 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3497 LHSClass = Type::ConstantArray;
3498 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3499 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003500
Nate Begeman213541a2008-04-18 23:10:10 +00003501 // Canonicalize ExtVector -> Vector.
3502 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3503 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003504
Chris Lattnerb0489812008-04-07 06:38:24 +00003505 // Consider qualified interfaces and interfaces the same.
Steve Naroff14108da2009-07-10 23:34:53 +00003506 // FIXME: Remove (ObjCObjectPointerType should obsolete this funny business).
Chris Lattnerb0489812008-04-07 06:38:24 +00003507 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3508 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003509
Chris Lattnera36a61f2008-04-07 05:43:21 +00003510 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003511 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003512 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3513 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003514 if (const EnumType* ETy = LHS->getAsEnumType()) {
3515 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3516 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003517 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003518 if (const EnumType* ETy = RHS->getAsEnumType()) {
3519 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3520 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003521 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003522
Eli Friedman3d815e72008-08-22 00:56:42 +00003523 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003524 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003525
Steve Naroff4a746782008-01-09 22:43:08 +00003526 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003527 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003528#define TYPE(Class, Base)
3529#define ABSTRACT_TYPE(Class, Base)
3530#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3531#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3532#include "clang/AST/TypeNodes.def"
3533 assert(false && "Non-canonical and dependent types shouldn't get here");
3534 return QualType();
3535
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003536 case Type::LValueReference:
3537 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003538 case Type::MemberPointer:
3539 assert(false && "C++ should never be in mergeTypes");
3540 return QualType();
3541
3542 case Type::IncompleteArray:
3543 case Type::VariableArray:
3544 case Type::FunctionProto:
3545 case Type::ExtVector:
3546 case Type::ObjCQualifiedInterface:
3547 assert(false && "Types are eliminated above");
3548 return QualType();
3549
Chris Lattner1adb8832008-01-14 05:45:46 +00003550 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003551 {
3552 // Merge two pointer types, while trying to preserve typedef info
3553 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3554 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3555 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3556 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003557 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003558 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003559 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003560 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003561 return getPointerType(ResultType);
3562 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003563 case Type::BlockPointer:
3564 {
3565 // Merge two block pointer types, while trying to preserve typedef info
3566 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3567 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3568 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3569 if (ResultType.isNull()) return QualType();
3570 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3571 return LHS;
3572 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3573 return RHS;
3574 return getBlockPointerType(ResultType);
3575 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003576 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003577 {
3578 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3579 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3580 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3581 return QualType();
3582
3583 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3584 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3585 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3586 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003587 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3588 return LHS;
3589 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3590 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003591 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3592 ArrayType::ArraySizeModifier(), 0);
3593 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3594 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003595 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3596 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003597 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3598 return LHS;
3599 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3600 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003601 if (LVAT) {
3602 // FIXME: This isn't correct! But tricky to implement because
3603 // the array's size has to be the size of LHS, but the type
3604 // has to be different.
3605 return LHS;
3606 }
3607 if (RVAT) {
3608 // FIXME: This isn't correct! But tricky to implement because
3609 // the array's size has to be the size of RHS, but the type
3610 // has to be different.
3611 return RHS;
3612 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003613 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3614 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003615 return getIncompleteArrayType(ResultType,
3616 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003617 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003618 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003619 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003620 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003621 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003622 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003623 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003624 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003625 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003626 case Type::Complex:
3627 // Distinct complex types are incompatible.
3628 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003629 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003630 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003631 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3632 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003633 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003634 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003635 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003636 // FIXME: This should be type compatibility, e.g. whether
3637 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003638 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3639 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3640 if (LHSIface && RHSIface &&
3641 canAssignObjCInterfaces(LHSIface, RHSIface))
3642 return LHS;
3643
Eli Friedman3d815e72008-08-22 00:56:42 +00003644 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003645 }
Steve Naroff14108da2009-07-10 23:34:53 +00003646 case Type::ObjCObjectPointer: {
3647 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3648 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3649 return QualType();
3650
3651 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3652 RHS->getAsObjCObjectPointerType()))
3653 return LHS;
3654
Steve Naroffbc76dd02008-12-10 22:14:21 +00003655 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003656 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003657 case Type::FixedWidthInt:
3658 // Distinct fixed-width integers are not compatible.
3659 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003660 case Type::ExtQual:
3661 // FIXME: ExtQual types can be compatible even if they're not
3662 // identical!
3663 return QualType();
3664 // First attempt at an implementation, but I'm not really sure it's
3665 // right...
3666#if 0
3667 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3668 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3669 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3670 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3671 return QualType();
3672 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3673 LHSBase = QualType(LQual->getBaseType(), 0);
3674 RHSBase = QualType(RQual->getBaseType(), 0);
3675 ResultType = mergeTypes(LHSBase, RHSBase);
3676 if (ResultType.isNull()) return QualType();
3677 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3678 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3679 return LHS;
3680 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3681 return RHS;
3682 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3683 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3684 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3685 return ResultType;
3686#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003687
3688 case Type::TemplateSpecialization:
3689 assert(false && "Dependent types have no size");
3690 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003691 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003692
3693 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003694}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003695
Chris Lattner5426bf62008-04-07 07:01:58 +00003696//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003697// Integer Predicates
3698//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003699
Eli Friedmanad74a752008-06-28 06:23:08 +00003700unsigned ASTContext::getIntWidth(QualType T) {
3701 if (T == BoolTy)
3702 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003703 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3704 return FWIT->getWidth();
3705 }
3706 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003707 return (unsigned)getTypeSize(T);
3708}
3709
3710QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3711 assert(T->isSignedIntegerType() && "Unexpected type");
3712 if (const EnumType* ETy = T->getAsEnumType())
3713 T = ETy->getDecl()->getIntegerType();
3714 const BuiltinType* BTy = T->getAsBuiltinType();
3715 assert (BTy && "Unexpected signed integer type");
3716 switch (BTy->getKind()) {
3717 case BuiltinType::Char_S:
3718 case BuiltinType::SChar:
3719 return UnsignedCharTy;
3720 case BuiltinType::Short:
3721 return UnsignedShortTy;
3722 case BuiltinType::Int:
3723 return UnsignedIntTy;
3724 case BuiltinType::Long:
3725 return UnsignedLongTy;
3726 case BuiltinType::LongLong:
3727 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003728 case BuiltinType::Int128:
3729 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003730 default:
3731 assert(0 && "Unexpected signed integer type");
3732 return QualType();
3733 }
3734}
3735
Douglas Gregor2cf26342009-04-09 22:27:44 +00003736ExternalASTSource::~ExternalASTSource() { }
3737
3738void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003739
3740
3741//===----------------------------------------------------------------------===//
3742// Builtin Type Computation
3743//===----------------------------------------------------------------------===//
3744
3745/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3746/// pointer over the consumed characters. This returns the resultant type.
3747static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3748 ASTContext::GetBuiltinTypeError &Error,
3749 bool AllowTypeModifiers = true) {
3750 // Modifiers.
3751 int HowLong = 0;
3752 bool Signed = false, Unsigned = false;
3753
3754 // Read the modifiers first.
3755 bool Done = false;
3756 while (!Done) {
3757 switch (*Str++) {
3758 default: Done = true; --Str; break;
3759 case 'S':
3760 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3761 assert(!Signed && "Can't use 'S' modifier multiple times!");
3762 Signed = true;
3763 break;
3764 case 'U':
3765 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3766 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3767 Unsigned = true;
3768 break;
3769 case 'L':
3770 assert(HowLong <= 2 && "Can't have LLLL modifier");
3771 ++HowLong;
3772 break;
3773 }
3774 }
3775
3776 QualType Type;
3777
3778 // Read the base type.
3779 switch (*Str++) {
3780 default: assert(0 && "Unknown builtin type letter!");
3781 case 'v':
3782 assert(HowLong == 0 && !Signed && !Unsigned &&
3783 "Bad modifiers used with 'v'!");
3784 Type = Context.VoidTy;
3785 break;
3786 case 'f':
3787 assert(HowLong == 0 && !Signed && !Unsigned &&
3788 "Bad modifiers used with 'f'!");
3789 Type = Context.FloatTy;
3790 break;
3791 case 'd':
3792 assert(HowLong < 2 && !Signed && !Unsigned &&
3793 "Bad modifiers used with 'd'!");
3794 if (HowLong)
3795 Type = Context.LongDoubleTy;
3796 else
3797 Type = Context.DoubleTy;
3798 break;
3799 case 's':
3800 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3801 if (Unsigned)
3802 Type = Context.UnsignedShortTy;
3803 else
3804 Type = Context.ShortTy;
3805 break;
3806 case 'i':
3807 if (HowLong == 3)
3808 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3809 else if (HowLong == 2)
3810 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3811 else if (HowLong == 1)
3812 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3813 else
3814 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3815 break;
3816 case 'c':
3817 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3818 if (Signed)
3819 Type = Context.SignedCharTy;
3820 else if (Unsigned)
3821 Type = Context.UnsignedCharTy;
3822 else
3823 Type = Context.CharTy;
3824 break;
3825 case 'b': // boolean
3826 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3827 Type = Context.BoolTy;
3828 break;
3829 case 'z': // size_t.
3830 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3831 Type = Context.getSizeType();
3832 break;
3833 case 'F':
3834 Type = Context.getCFConstantStringType();
3835 break;
3836 case 'a':
3837 Type = Context.getBuiltinVaListType();
3838 assert(!Type.isNull() && "builtin va list type not initialized!");
3839 break;
3840 case 'A':
3841 // This is a "reference" to a va_list; however, what exactly
3842 // this means depends on how va_list is defined. There are two
3843 // different kinds of va_list: ones passed by value, and ones
3844 // passed by reference. An example of a by-value va_list is
3845 // x86, where va_list is a char*. An example of by-ref va_list
3846 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3847 // we want this argument to be a char*&; for x86-64, we want
3848 // it to be a __va_list_tag*.
3849 Type = Context.getBuiltinVaListType();
3850 assert(!Type.isNull() && "builtin va list type not initialized!");
3851 if (Type->isArrayType()) {
3852 Type = Context.getArrayDecayedType(Type);
3853 } else {
3854 Type = Context.getLValueReferenceType(Type);
3855 }
3856 break;
3857 case 'V': {
3858 char *End;
3859
3860 unsigned NumElements = strtoul(Str, &End, 10);
3861 assert(End != Str && "Missing vector size");
3862
3863 Str = End;
3864
3865 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3866 Type = Context.getVectorType(ElementType, NumElements);
3867 break;
3868 }
3869 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003870 Type = Context.getFILEType();
3871 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003872 Error = ASTContext::GE_Missing_FILE;
3873 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003874 } else {
3875 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003876 }
3877 }
3878 }
3879
3880 if (!AllowTypeModifiers)
3881 return Type;
3882
3883 Done = false;
3884 while (!Done) {
3885 switch (*Str++) {
3886 default: Done = true; --Str; break;
3887 case '*':
3888 Type = Context.getPointerType(Type);
3889 break;
3890 case '&':
3891 Type = Context.getLValueReferenceType(Type);
3892 break;
3893 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3894 case 'C':
3895 Type = Type.getQualifiedType(QualType::Const);
3896 break;
3897 }
3898 }
3899
3900 return Type;
3901}
3902
3903/// GetBuiltinType - Return the type for the specified builtin.
3904QualType ASTContext::GetBuiltinType(unsigned id,
3905 GetBuiltinTypeError &Error) {
3906 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3907
3908 llvm::SmallVector<QualType, 8> ArgTypes;
3909
3910 Error = GE_None;
3911 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3912 if (Error != GE_None)
3913 return QualType();
3914 while (TypeStr[0] && TypeStr[0] != '.') {
3915 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3916 if (Error != GE_None)
3917 return QualType();
3918
3919 // Do array -> pointer decay. The builtin should use the decayed type.
3920 if (Ty->isArrayType())
3921 Ty = getArrayDecayedType(Ty);
3922
3923 ArgTypes.push_back(Ty);
3924 }
3925
3926 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3927 "'.' should only occur at end of builtin type list!");
3928
3929 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3930 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3931 return getFunctionNoProtoType(ResType);
3932 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3933 TypeStr[0] == '.', 0);
3934}