blob: b43aadb62e4ac7188762858bfa032aa6c3fe2fa5 [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"
Anders Carlsson3d598a52009-07-14 17:29:11 +000015#include "clang/AST/ASTRecordLayout.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.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 Naroffde2e22d2009-07-15 18:40:39 +0000204 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
205 ObjCIdTypedefType = QualType();
206 ObjCClassTypedefType = QualType();
207
208 // Builtin types for 'id' and 'Class'.
209 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
210 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000211
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000212 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000213
214 // void * type
215 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000216
217 // nullptr type (C++0x 2.14.7)
218 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000219}
220
Douglas Gregor2e222532009-07-02 17:08:52 +0000221namespace {
222 class BeforeInTranslationUnit
223 : std::binary_function<SourceRange, SourceRange, bool> {
224 SourceManager *SourceMgr;
225
226 public:
227 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
228
229 bool operator()(SourceRange X, SourceRange Y) {
230 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
231 }
232 };
233}
234
235/// \brief Determine whether the given comment is a Doxygen-style comment.
236///
237/// \param Start the start of the comment text.
238///
239/// \param End the end of the comment text.
240///
241/// \param Member whether we want to check whether this is a member comment
242/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
243/// we only return true when we find a non-member comment.
244static bool
245isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
246 bool Member = false) {
247 const char *BufferStart
248 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
249 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
250 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
251
252 if (End - Start < 4)
253 return false;
254
255 assert(Start[0] == '/' && "Not a comment?");
256 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
257 return false;
258 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
259 return false;
260
261 return (Start[3] == '<') == Member;
262}
263
264/// \brief Retrieve the comment associated with the given declaration, if
265/// it has one.
266const char *ASTContext::getCommentForDecl(const Decl *D) {
267 if (!D)
268 return 0;
269
270 // Check whether we have cached a comment string for this declaration
271 // already.
272 llvm::DenseMap<const Decl *, std::string>::iterator Pos
273 = DeclComments.find(D);
274 if (Pos != DeclComments.end())
275 return Pos->second.c_str();
276
277 // If we have an external AST source and have not yet loaded comments from
278 // that source, do so now.
279 if (ExternalSource && !LoadedExternalComments) {
280 std::vector<SourceRange> LoadedComments;
281 ExternalSource->ReadComments(LoadedComments);
282
283 if (!LoadedComments.empty())
284 Comments.insert(Comments.begin(), LoadedComments.begin(),
285 LoadedComments.end());
286
287 LoadedExternalComments = true;
288 }
289
290 // If there are no comments anywhere, we won't find anything.
291 if (Comments.empty())
292 return 0;
293
294 // If the declaration doesn't map directly to a location in a file, we
295 // can't find the comment.
296 SourceLocation DeclStartLoc = D->getLocStart();
297 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
298 return 0;
299
300 // Find the comment that occurs just before this declaration.
301 std::vector<SourceRange>::iterator LastComment
302 = std::lower_bound(Comments.begin(), Comments.end(),
303 SourceRange(DeclStartLoc),
304 BeforeInTranslationUnit(&SourceMgr));
305
306 // Decompose the location for the start of the declaration and find the
307 // beginning of the file buffer.
308 std::pair<FileID, unsigned> DeclStartDecomp
309 = SourceMgr.getDecomposedLoc(DeclStartLoc);
310 const char *FileBufferStart
311 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
312
313 // First check whether we have a comment for a member.
314 if (LastComment != Comments.end() &&
315 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
316 isDoxygenComment(SourceMgr, *LastComment, true)) {
317 std::pair<FileID, unsigned> LastCommentEndDecomp
318 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
319 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
320 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
321 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
322 LastCommentEndDecomp.second)) {
323 // The Doxygen member comment comes after the declaration starts and
324 // is on the same line and in the same file as the declaration. This
325 // is the comment we want.
326 std::string &Result = DeclComments[D];
327 Result.append(FileBufferStart +
328 SourceMgr.getFileOffset(LastComment->getBegin()),
329 FileBufferStart + LastCommentEndDecomp.second + 1);
330 return Result.c_str();
331 }
332 }
333
334 if (LastComment == Comments.begin())
335 return 0;
336 --LastComment;
337
338 // Decompose the end of the comment.
339 std::pair<FileID, unsigned> LastCommentEndDecomp
340 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
341
342 // If the comment and the declaration aren't in the same file, then they
343 // aren't related.
344 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
345 return 0;
346
347 // Check that we actually have a Doxygen comment.
348 if (!isDoxygenComment(SourceMgr, *LastComment))
349 return 0;
350
351 // Compute the starting line for the declaration and for the end of the
352 // comment (this is expensive).
353 unsigned DeclStartLine
354 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
355 unsigned CommentEndLine
356 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
357 LastCommentEndDecomp.second);
358
359 // If the comment does not end on the line prior to the declaration, then
360 // the comment is not associated with the declaration at all.
361 if (CommentEndLine + 1 != DeclStartLine)
362 return 0;
363
364 // We have a comment, but there may be more comments on the previous lines.
365 // Keep looking so long as the comments are still Doxygen comments and are
366 // still adjacent.
367 unsigned ExpectedLine
368 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
369 std::vector<SourceRange>::iterator FirstComment = LastComment;
370 while (FirstComment != Comments.begin()) {
371 // Look at the previous comment
372 --FirstComment;
373 std::pair<FileID, unsigned> Decomp
374 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
375
376 // If this previous comment is in a different file, we're done.
377 if (Decomp.first != DeclStartDecomp.first) {
378 ++FirstComment;
379 break;
380 }
381
382 // If this comment is not a Doxygen comment, we're done.
383 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
384 ++FirstComment;
385 break;
386 }
387
388 // If the line number is not what we expected, we're done.
389 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
390 if (Line != ExpectedLine) {
391 ++FirstComment;
392 break;
393 }
394
395 // Set the next expected line number.
396 ExpectedLine
397 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
398 }
399
400 // The iterator range [FirstComment, LastComment] contains all of the
401 // BCPL comments that, together, are associated with this declaration.
402 // Form a single comment block string for this declaration that concatenates
403 // all of these comments.
404 std::string &Result = DeclComments[D];
405 while (FirstComment != LastComment) {
406 std::pair<FileID, unsigned> DecompStart
407 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
408 std::pair<FileID, unsigned> DecompEnd
409 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
410 Result.append(FileBufferStart + DecompStart.second,
411 FileBufferStart + DecompEnd.second + 1);
412 ++FirstComment;
413 }
414
415 // Append the last comment line.
416 Result.append(FileBufferStart +
417 SourceMgr.getFileOffset(LastComment->getBegin()),
418 FileBufferStart + LastCommentEndDecomp.second + 1);
419 return Result.c_str();
420}
421
Chris Lattner464175b2007-07-18 17:52:12 +0000422//===----------------------------------------------------------------------===//
423// Type Sizing and Analysis
424//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000425
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000426/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
427/// scalar floating point type.
428const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
429 const BuiltinType *BT = T->getAsBuiltinType();
430 assert(BT && "Not a floating point type!");
431 switch (BT->getKind()) {
432 default: assert(0 && "Not a floating point type!");
433 case BuiltinType::Float: return Target.getFloatFormat();
434 case BuiltinType::Double: return Target.getDoubleFormat();
435 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
436 }
437}
438
Chris Lattneraf707ab2009-01-24 21:53:27 +0000439/// getDeclAlign - Return a conservative estimate of the alignment of the
440/// specified decl. Note that bitfields do not have a valid alignment, so
441/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000442unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000443 unsigned Align = Target.getCharWidth();
444
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000445 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000446 Align = std::max(Align, AA->getAlignment());
447
Chris Lattneraf707ab2009-01-24 21:53:27 +0000448 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
449 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000450 if (const ReferenceType* RT = T->getAsReferenceType()) {
451 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000452 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000453 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
454 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000455 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
456 T = cast<ArrayType>(T)->getElementType();
457
458 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
459 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000460 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000461
462 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000463}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000464
Chris Lattnera7674d82007-07-13 22:13:22 +0000465/// getTypeSize - Return the size of the specified type, in bits. This method
466/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000467std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000468ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000469 uint64_t Width=0;
470 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000471 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000472#define TYPE(Class, Base)
473#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000474#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000475#define DEPENDENT_TYPE(Class, Base) case Type::Class:
476#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000477 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000478 break;
479
Chris Lattner692233e2007-07-13 22:27:08 +0000480 case Type::FunctionNoProto:
481 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000482 // GCC extension: alignof(function) = 32 bits
483 Width = 0;
484 Align = 32;
485 break;
486
Douglas Gregor72564e72009-02-26 23:50:07 +0000487 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000488 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000489 Width = 0;
490 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
491 break;
492
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000493 case Type::ConstantArrayWithExpr:
494 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000495 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000496 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000497
Chris Lattner98be4942008-03-05 18:54:05 +0000498 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000499 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000500 Align = EltInfo.second;
501 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000502 }
Nate Begeman213541a2008-04-18 23:10:10 +0000503 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000504 case Type::Vector: {
505 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000506 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000507 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000508 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000509 // If the alignment is not a power of 2, round up to the next power of 2.
510 // This happens for non-power-of-2 length vectors.
511 // FIXME: this should probably be a target property.
512 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000513 break;
514 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000515
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000516 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000517 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000518 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000519 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000520 // GCC extension: alignof(void) = 8 bits.
521 Width = 0;
522 Align = 8;
523 break;
524
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000525 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000526 Width = Target.getBoolWidth();
527 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000528 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000529 case BuiltinType::Char_S:
530 case BuiltinType::Char_U:
531 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000532 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000533 Width = Target.getCharWidth();
534 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000535 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000536 case BuiltinType::WChar:
537 Width = Target.getWCharWidth();
538 Align = Target.getWCharAlign();
539 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000540 case BuiltinType::Char16:
541 Width = Target.getChar16Width();
542 Align = Target.getChar16Align();
543 break;
544 case BuiltinType::Char32:
545 Width = Target.getChar32Width();
546 Align = Target.getChar32Align();
547 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000548 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000549 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000550 Width = Target.getShortWidth();
551 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000552 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000553 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000555 Width = Target.getIntWidth();
556 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000557 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000558 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000560 Width = Target.getLongWidth();
561 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000562 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000563 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000564 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000565 Width = Target.getLongLongWidth();
566 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000567 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000568 case BuiltinType::Int128:
569 case BuiltinType::UInt128:
570 Width = 128;
571 Align = 128; // int128_t is 128-bit aligned on all targets.
572 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000573 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000574 Width = Target.getFloatWidth();
575 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000576 break;
577 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000578 Width = Target.getDoubleWidth();
579 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000580 break;
581 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000582 Width = Target.getLongDoubleWidth();
583 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000584 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000585 case BuiltinType::NullPtr:
586 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
587 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000588 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000589 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000590 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000591 case Type::FixedWidthInt:
592 // FIXME: This isn't precisely correct; the width/alignment should depend
593 // on the available types for the target
594 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000595 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000596 Align = Width;
597 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000598 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000599 // FIXME: Pointers into different addr spaces could have different sizes and
600 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000601 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000602 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000603 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000604 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000605 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000606 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000607 case Type::BlockPointer: {
608 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
609 Width = Target.getPointerWidth(AS);
610 Align = Target.getPointerAlign(AS);
611 break;
612 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000613 case Type::Pointer: {
614 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000615 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000616 Align = Target.getPointerAlign(AS);
617 break;
618 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000619 case Type::LValueReference:
620 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000621 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000622 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000623 // FIXME: This is wrong for struct layout: a reference in a struct has
624 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000625 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000626 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000627 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
628 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
629 // If we ever want to support other ABIs this needs to be abstracted.
630
Sebastian Redlf30208a2009-01-24 21:16:55 +0000631 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000632 std::pair<uint64_t, unsigned> PtrDiffInfo =
633 getTypeInfo(getPointerDiffType());
634 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000635 if (Pointee->isFunctionType())
636 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000637 Align = PtrDiffInfo.second;
638 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000639 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000640 case Type::Complex: {
641 // Complex types have the same alignment as their elements, but twice the
642 // size.
643 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000644 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000645 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000646 Align = EltInfo.second;
647 break;
648 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000649 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000650 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000651 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
652 Width = Layout.getSize();
653 Align = Layout.getAlignment();
654 break;
655 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000656 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000657 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000658 const TagType *TT = cast<TagType>(T);
659
660 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000661 Width = 1;
662 Align = 1;
663 break;
664 }
665
Daniel Dunbar1d751182008-11-08 05:48:37 +0000666 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000667 return getTypeInfo(ET->getDecl()->getIntegerType());
668
Daniel Dunbar1d751182008-11-08 05:48:37 +0000669 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000670 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
671 Width = Layout.getSize();
672 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000673 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000674 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000675
Douglas Gregor18857642009-04-30 17:32:17 +0000676 case Type::Typedef: {
677 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000678 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000679 Align = Aligned->getAlignment();
680 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
681 } else
682 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000683 break;
Chris Lattner71763312008-04-06 22:05:18 +0000684 }
Douglas Gregor18857642009-04-30 17:32:17 +0000685
686 case Type::TypeOfExpr:
687 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
688 .getTypePtr());
689
690 case Type::TypeOf:
691 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
692
Anders Carlsson395b4752009-06-24 19:06:50 +0000693 case Type::Decltype:
694 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
695 .getTypePtr());
696
Douglas Gregor18857642009-04-30 17:32:17 +0000697 case Type::QualifiedName:
698 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
699
700 case Type::TemplateSpecialization:
701 assert(getCanonicalType(T) != T &&
702 "Cannot request the size of a dependent type");
703 // FIXME: this is likely to be wrong once we support template
704 // aliases, since a template alias could refer to a typedef that
705 // has an __aligned__ attribute on it.
706 return getTypeInfo(getCanonicalType(T));
707 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000708
Chris Lattner464175b2007-07-18 17:52:12 +0000709 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000710 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000711}
712
Chris Lattner34ebde42009-01-27 18:08:34 +0000713/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
714/// type for the current target in bits. This can be different than the ABI
715/// alignment in cases where it is beneficial for performance to overalign
716/// a data type.
717unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
718 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000719
720 // Double and long long should be naturally aligned if possible.
721 if (const ComplexType* CT = T->getAsComplexType())
722 T = CT->getElementType().getTypePtr();
723 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
724 T->isSpecificBuiltinType(BuiltinType::LongLong))
725 return std::max(ABIAlign, (unsigned)getTypeSize(T));
726
Chris Lattner34ebde42009-01-27 18:08:34 +0000727 return ABIAlign;
728}
729
730
Devang Patel8b277042008-06-04 21:22:16 +0000731/// LayoutField - Field layout.
732void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000733 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000734 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000735 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000736 uint64_t FieldOffset = IsUnion ? 0 : Size;
737 uint64_t FieldSize;
738 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000739
740 // FIXME: Should this override struct packing? Probably we want to
741 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000742 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000743 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000744
745 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
746 // TODO: Need to check this algorithm on other targets!
747 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000748 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000749
750 std::pair<uint64_t, unsigned> FieldInfo =
751 Context.getTypeInfo(FD->getType());
752 uint64_t TypeSize = FieldInfo.first;
753
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000754 // Determine the alignment of this bitfield. The packing
755 // attributes define a maximum and the alignment attribute defines
756 // a minimum.
757 // FIXME: What is the right behavior when the specified alignment
758 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000759 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000760 if (FieldPacking)
761 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000762 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000763 FieldAlign = std::max(FieldAlign, AA->getAlignment());
764
765 // Check if we need to add padding to give the field the correct
766 // alignment.
767 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
768 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
769
770 // Padding members don't affect overall alignment
771 if (!FD->getIdentifier())
772 FieldAlign = 1;
773 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000774 if (FD->getType()->isIncompleteArrayType()) {
775 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000776 // query getTypeInfo about these, so we figure it out here.
777 // Flexible array members don't have any size, but they
778 // have to be aligned appropriately for their element type.
779 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000780 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000781 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000782 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
783 unsigned AS = RT->getPointeeType().getAddressSpace();
784 FieldSize = Context.Target.getPointerWidth(AS);
785 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000786 } else {
787 std::pair<uint64_t, unsigned> FieldInfo =
788 Context.getTypeInfo(FD->getType());
789 FieldSize = FieldInfo.first;
790 FieldAlign = FieldInfo.second;
791 }
792
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000793 // Determine the alignment of this bitfield. The packing
794 // attributes define a maximum and the alignment attribute defines
795 // a minimum. Additionally, the packing alignment must be at least
796 // a byte for non-bitfields.
797 //
798 // FIXME: What is the right behavior when the specified alignment
799 // is smaller than the specified packing?
800 if (FieldPacking)
801 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000802 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000803 FieldAlign = std::max(FieldAlign, AA->getAlignment());
804
805 // Round up the current record size to the field's alignment boundary.
806 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
807 }
808
809 // Place this field at the current location.
810 FieldOffsets[FieldNo] = FieldOffset;
811
812 // Reserve space for this field.
813 if (IsUnion) {
814 Size = std::max(Size, FieldSize);
815 } else {
816 Size = FieldOffset + FieldSize;
817 }
818
Daniel Dunbard6884a02009-05-04 05:16:21 +0000819 // Remember the next available offset.
820 NextOffset = Size;
821
Devang Patel8b277042008-06-04 21:22:16 +0000822 // Remember max struct/class alignment.
823 Alignment = std::max(Alignment, FieldAlign);
824}
825
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000826static void CollectLocalObjCIvars(ASTContext *Ctx,
827 const ObjCInterfaceDecl *OI,
828 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000829 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
830 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000831 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000832 if (!IVDecl->isInvalidDecl())
833 Fields.push_back(cast<FieldDecl>(IVDecl));
834 }
835}
836
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000837void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
838 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
839 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
840 CollectObjCIvars(SuperClass, Fields);
841 CollectLocalObjCIvars(this, OI, Fields);
842}
843
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000844/// ShallowCollectObjCIvars -
845/// Collect all ivars, including those synthesized, in the current class.
846///
847void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
848 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
849 bool CollectSynthesized) {
850 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
851 E = OI->ivar_end(); I != E; ++I) {
852 Ivars.push_back(*I);
853 }
854 if (CollectSynthesized)
855 CollectSynthesizedIvars(OI, Ivars);
856}
857
Fariborz Jahanian98200742009-05-12 18:14:29 +0000858void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
859 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000860 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
861 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000862 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
863 Ivars.push_back(Ivar);
864
865 // Also look into nested protocols.
866 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
867 E = PD->protocol_end(); P != E; ++P)
868 CollectProtocolSynthesizedIvars(*P, Ivars);
869}
870
871/// CollectSynthesizedIvars -
872/// This routine collect synthesized ivars for the designated class.
873///
874void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000876 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
877 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000878 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
879 Ivars.push_back(Ivar);
880 }
881 // Also look into interface's protocol list for properties declared
882 // in the protocol and whose ivars are synthesized.
883 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
884 PE = OI->protocol_end(); P != PE; ++P) {
885 ObjCProtocolDecl *PD = (*P);
886 CollectProtocolSynthesizedIvars(PD, Ivars);
887 }
888}
889
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000890unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
891 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000892 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
893 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000894 if ((*I)->getPropertyIvarDecl())
895 ++count;
896
897 // Also look into nested protocols.
898 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
899 E = PD->protocol_end(); P != E; ++P)
900 count += CountProtocolSynthesizedIvars(*P);
901 return count;
902}
903
904unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
905{
906 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000907 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
908 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000909 if ((*I)->getPropertyIvarDecl())
910 ++count;
911 }
912 // Also look into interface's protocol list for properties declared
913 // in the protocol and whose ivars are synthesized.
914 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
915 PE = OI->protocol_end(); P != PE; ++P) {
916 ObjCProtocolDecl *PD = (*P);
917 count += CountProtocolSynthesizedIvars(PD);
918 }
919 return count;
920}
921
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000922/// getInterfaceLayoutImpl - Get or compute information about the
923/// layout of the given interface.
924///
925/// \param Impl - If given, also include the layout of the interface's
926/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000927const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000928ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
929 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000930 assert(!D->isForwardDecl() && "Invalid interface decl!");
931
Devang Patel44a3dde2008-06-04 21:54:36 +0000932 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000933 ObjCContainerDecl *Key =
934 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
935 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
936 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000937
Daniel Dunbar453addb2009-05-03 11:16:44 +0000938 unsigned FieldCount = D->ivar_size();
939 // Add in synthesized ivar count if laying out an implementation.
940 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000941 unsigned SynthCount = CountSynthesizedIvars(D);
942 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000943 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000944 // entry. Note we can't cache this because we simply free all
945 // entries later; however we shouldn't look up implementations
946 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000947 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000948 return getObjCLayout(D, 0);
949 }
950
Devang Patel6a5a34c2008-06-06 02:14:01 +0000951 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000952 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000953 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
954 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000955
Daniel Dunbar913af352009-05-07 21:58:26 +0000956 // We start laying out ivars not at the end of the superclass
957 // structure, but at the next byte following the last field.
958 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000959
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000960 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000961 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000962 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000963 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000964 NewEntry->InitializeLayout(FieldCount);
965 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000966
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000967 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000968 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000969 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000970
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000971 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000972 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
973 AA->getAlignment()));
974
975 // Layout each ivar sequentially.
976 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000977 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
978 ShallowCollectObjCIvars(D, Ivars, Impl);
979 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
980 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
981
Devang Patel44a3dde2008-06-04 21:54:36 +0000982 // Finally, round the size of the total struct up to the alignment of the
983 // struct itself.
984 NewEntry->FinalizeLayout();
985 return *NewEntry;
986}
987
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000988const ASTRecordLayout &
989ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
990 return getObjCLayout(D, 0);
991}
992
993const ASTRecordLayout &
994ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
995 return getObjCLayout(D->getClassInterface(), D);
996}
997
Devang Patel88a981b2007-11-01 19:11:01 +0000998/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000999/// specified record (struct/union/class), which indicates its size and field
1000/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001001const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001002 D = D->getDefinition(*this);
1003 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001004
Chris Lattner464175b2007-07-18 17:52:12 +00001005 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +00001006 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001007 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001008
Devang Patel88a981b2007-11-01 19:11:01 +00001009 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
1010 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
1011 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +00001012 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001013
Douglas Gregore267ff32008-12-11 20:41:00 +00001014 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001015 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001016 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +00001017
Daniel Dunbar3b0db902008-10-16 02:34:03 +00001018 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001019 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +00001020 StructPacking = PA->getAlignment();
1021
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001022 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +00001023 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1024 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001025
Eli Friedman4bd998b2008-05-30 09:31:38 +00001026 // Layout each field, for now, just sequentially, respecting alignment. In
1027 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001028 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001029 for (RecordDecl::field_iterator Field = D->field_begin(),
1030 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001031 Field != FieldEnd; (void)++Field, ++FieldIdx)
1032 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001033
1034 // Finally, round the size of the total struct up to the alignment of the
1035 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001036 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001037 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001038}
1039
Chris Lattnera7674d82007-07-13 22:13:22 +00001040//===----------------------------------------------------------------------===//
1041// Type creation/memoization methods
1042//===----------------------------------------------------------------------===//
1043
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001044QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001045 QualType CanT = getCanonicalType(T);
1046 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001047 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001048
1049 // If we are composing extended qualifiers together, merge together into one
1050 // ExtQualType node.
1051 unsigned CVRQuals = T.getCVRQualifiers();
1052 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1053 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001054
Chris Lattnerb7d25532009-02-18 22:53:11 +00001055 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1056 // If this type already has an address space specified, it cannot get
1057 // another one.
1058 assert(EQT->getAddressSpace() == 0 &&
1059 "Type cannot be in multiple addr spaces!");
1060 GCAttr = EQT->getObjCGCAttr();
1061 TypeNode = EQT->getBaseType();
1062 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001063
Chris Lattnerb7d25532009-02-18 22:53:11 +00001064 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001065 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001066 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001067 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001068 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001069 return QualType(EXTQy, CVRQuals);
1070
Christopher Lambebb97e92008-02-04 02:31:56 +00001071 // If the base type isn't canonical, this won't be a canonical type either,
1072 // so fill in the canonical type field.
1073 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001074 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001075 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001076
Chris Lattnerb7d25532009-02-18 22:53:11 +00001077 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001078 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001079 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001080 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001081 ExtQualType *New =
1082 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001083 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001084 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001085 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001086}
1087
Chris Lattnerb7d25532009-02-18 22:53:11 +00001088QualType ASTContext::getObjCGCQualType(QualType T,
1089 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001090 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001091 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001092 return T;
1093
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001094 if (T->isPointerType()) {
1095 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001096 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001097 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1098 return getPointerType(ResultType);
1099 }
1100 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001101 // If we are composing extended qualifiers together, merge together into one
1102 // ExtQualType node.
1103 unsigned CVRQuals = T.getCVRQualifiers();
1104 Type *TypeNode = T.getTypePtr();
1105 unsigned AddressSpace = 0;
1106
1107 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1108 // If this type already has an address space specified, it cannot get
1109 // another one.
1110 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1111 "Type cannot be in multiple addr spaces!");
1112 AddressSpace = EQT->getAddressSpace();
1113 TypeNode = EQT->getBaseType();
1114 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001115
1116 // Check if we've already instantiated an gc qual'd type of this type.
1117 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001118 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001119 void *InsertPos = 0;
1120 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001121 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001122
1123 // If the base type isn't canonical, this won't be a canonical type either,
1124 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001125 // FIXME: Isn't this also not canonical if the base type is a array
1126 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001127 QualType Canonical;
1128 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001129 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001130
Chris Lattnerb7d25532009-02-18 22:53:11 +00001131 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001132 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1133 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1134 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001135 ExtQualType *New =
1136 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001137 ExtQualTypes.InsertNode(New, InsertPos);
1138 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001139 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001140}
Chris Lattnera7674d82007-07-13 22:13:22 +00001141
Reid Spencer5f016e22007-07-11 17:01:13 +00001142/// getComplexType - Return the uniqued reference to the type for a complex
1143/// number with the specified element type.
1144QualType ASTContext::getComplexType(QualType T) {
1145 // Unique pointers, to guarantee there is only one pointer of a particular
1146 // structure.
1147 llvm::FoldingSetNodeID ID;
1148 ComplexType::Profile(ID, T);
1149
1150 void *InsertPos = 0;
1151 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1152 return QualType(CT, 0);
1153
1154 // If the pointee type isn't canonical, this won't be a canonical type either,
1155 // so fill in the canonical type field.
1156 QualType Canonical;
1157 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001158 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001159
1160 // Get the new insert position for the node we care about.
1161 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001162 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 }
Steve Narofff83820b2009-01-27 22:08:43 +00001164 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 Types.push_back(New);
1166 ComplexTypes.InsertNode(New, InsertPos);
1167 return QualType(New, 0);
1168}
1169
Eli Friedmanf98aba32009-02-13 02:31:07 +00001170QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1171 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1172 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1173 FixedWidthIntType *&Entry = Map[Width];
1174 if (!Entry)
1175 Entry = new FixedWidthIntType(Width, Signed);
1176 return QualType(Entry, 0);
1177}
Reid Spencer5f016e22007-07-11 17:01:13 +00001178
1179/// getPointerType - Return the uniqued reference to the type for a pointer to
1180/// the specified type.
1181QualType ASTContext::getPointerType(QualType T) {
1182 // Unique pointers, to guarantee there is only one pointer of a particular
1183 // structure.
1184 llvm::FoldingSetNodeID ID;
1185 PointerType::Profile(ID, T);
1186
1187 void *InsertPos = 0;
1188 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1189 return QualType(PT, 0);
1190
1191 // If the pointee type isn't canonical, this won't be a canonical type either,
1192 // so fill in the canonical type field.
1193 QualType Canonical;
1194 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001195 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001196
1197 // Get the new insert position for the node we care about.
1198 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001199 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 }
Steve Narofff83820b2009-01-27 22:08:43 +00001201 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 Types.push_back(New);
1203 PointerTypes.InsertNode(New, InsertPos);
1204 return QualType(New, 0);
1205}
1206
Steve Naroff5618bd42008-08-27 16:04:49 +00001207/// getBlockPointerType - Return the uniqued reference to the type for
1208/// a pointer to the specified block.
1209QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001210 assert(T->isFunctionType() && "block of function types only");
1211 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001212 // structure.
1213 llvm::FoldingSetNodeID ID;
1214 BlockPointerType::Profile(ID, T);
1215
1216 void *InsertPos = 0;
1217 if (BlockPointerType *PT =
1218 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1219 return QualType(PT, 0);
1220
Steve Naroff296e8d52008-08-28 19:20:44 +00001221 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001222 // type either so fill in the canonical type field.
1223 QualType Canonical;
1224 if (!T->isCanonical()) {
1225 Canonical = getBlockPointerType(getCanonicalType(T));
1226
1227 // Get the new insert position for the node we care about.
1228 BlockPointerType *NewIP =
1229 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001230 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001231 }
Steve Narofff83820b2009-01-27 22:08:43 +00001232 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001233 Types.push_back(New);
1234 BlockPointerTypes.InsertNode(New, InsertPos);
1235 return QualType(New, 0);
1236}
1237
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001238/// getLValueReferenceType - Return the uniqued reference to the type for an
1239/// lvalue reference to the specified type.
1240QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 // Unique pointers, to guarantee there is only one pointer of a particular
1242 // structure.
1243 llvm::FoldingSetNodeID ID;
1244 ReferenceType::Profile(ID, T);
1245
1246 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001247 if (LValueReferenceType *RT =
1248 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001250
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 // If the referencee type isn't canonical, this won't be a canonical type
1252 // either, so fill in the canonical type field.
1253 QualType Canonical;
1254 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001255 Canonical = getLValueReferenceType(getCanonicalType(T));
1256
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001258 LValueReferenceType *NewIP =
1259 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001260 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 }
1262
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001263 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001265 LValueReferenceTypes.InsertNode(New, InsertPos);
1266 return QualType(New, 0);
1267}
1268
1269/// getRValueReferenceType - Return the uniqued reference to the type for an
1270/// rvalue reference to the specified type.
1271QualType ASTContext::getRValueReferenceType(QualType T) {
1272 // Unique pointers, to guarantee there is only one pointer of a particular
1273 // structure.
1274 llvm::FoldingSetNodeID ID;
1275 ReferenceType::Profile(ID, T);
1276
1277 void *InsertPos = 0;
1278 if (RValueReferenceType *RT =
1279 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1280 return QualType(RT, 0);
1281
1282 // If the referencee type isn't canonical, this won't be a canonical type
1283 // either, so fill in the canonical type field.
1284 QualType Canonical;
1285 if (!T->isCanonical()) {
1286 Canonical = getRValueReferenceType(getCanonicalType(T));
1287
1288 // Get the new insert position for the node we care about.
1289 RValueReferenceType *NewIP =
1290 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1291 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1292 }
1293
1294 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1295 Types.push_back(New);
1296 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 return QualType(New, 0);
1298}
1299
Sebastian Redlf30208a2009-01-24 21:16:55 +00001300/// getMemberPointerType - Return the uniqued reference to the type for a
1301/// member pointer to the specified type, in the specified class.
1302QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1303{
1304 // Unique pointers, to guarantee there is only one pointer of a particular
1305 // structure.
1306 llvm::FoldingSetNodeID ID;
1307 MemberPointerType::Profile(ID, T, Cls);
1308
1309 void *InsertPos = 0;
1310 if (MemberPointerType *PT =
1311 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1312 return QualType(PT, 0);
1313
1314 // If the pointee or class type isn't canonical, this won't be a canonical
1315 // type either, so fill in the canonical type field.
1316 QualType Canonical;
1317 if (!T->isCanonical()) {
1318 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1319
1320 // Get the new insert position for the node we care about.
1321 MemberPointerType *NewIP =
1322 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1323 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1324 }
Steve Narofff83820b2009-01-27 22:08:43 +00001325 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001326 Types.push_back(New);
1327 MemberPointerTypes.InsertNode(New, InsertPos);
1328 return QualType(New, 0);
1329}
1330
Steve Narofffb22d962007-08-30 01:06:46 +00001331/// getConstantArrayType - Return the unique reference to the type for an
1332/// array of the specified element type.
1333QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001334 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001335 ArrayType::ArraySizeModifier ASM,
1336 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001337 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1338 "Constant array of VLAs is illegal!");
1339
Chris Lattner38aeec72009-05-13 04:12:56 +00001340 // Convert the array size into a canonical width matching the pointer size for
1341 // the target.
1342 llvm::APInt ArySize(ArySizeIn);
1343 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001346 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001347
1348 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001349 if (ConstantArrayType *ATP =
1350 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 return QualType(ATP, 0);
1352
1353 // If the element type isn't canonical, this won't be a canonical type either,
1354 // so fill in the canonical type field.
1355 QualType Canonical;
1356 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001357 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001358 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001360 ConstantArrayType *NewIP =
1361 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001362 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 }
1364
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001365 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001366 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001367 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 Types.push_back(New);
1369 return QualType(New, 0);
1370}
1371
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001372/// getConstantArrayWithExprType - Return a reference to the type for
1373/// an array of the specified element type.
1374QualType
1375ASTContext::getConstantArrayWithExprType(QualType EltTy,
1376 const llvm::APInt &ArySizeIn,
1377 Expr *ArySizeExpr,
1378 ArrayType::ArraySizeModifier ASM,
1379 unsigned EltTypeQuals,
1380 SourceRange Brackets) {
1381 // Convert the array size into a canonical width matching the pointer
1382 // size for the target.
1383 llvm::APInt ArySize(ArySizeIn);
1384 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1385
1386 // Compute the canonical ConstantArrayType.
1387 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1388 ArySize, ASM, EltTypeQuals);
1389 // Since we don't unique expressions, it isn't possible to unique VLA's
1390 // that have an expression provided for their size.
1391 ConstantArrayWithExprType *New =
1392 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1393 ArySize, ArySizeExpr,
1394 ASM, EltTypeQuals, Brackets);
1395 Types.push_back(New);
1396 return QualType(New, 0);
1397}
1398
1399/// getConstantArrayWithoutExprType - Return a reference to the type for
1400/// an array of the specified element type.
1401QualType
1402ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1403 const llvm::APInt &ArySizeIn,
1404 ArrayType::ArraySizeModifier ASM,
1405 unsigned EltTypeQuals) {
1406 // Convert the array size into a canonical width matching the pointer
1407 // size for the target.
1408 llvm::APInt ArySize(ArySizeIn);
1409 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1410
1411 // Compute the canonical ConstantArrayType.
1412 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1413 ArySize, ASM, EltTypeQuals);
1414 ConstantArrayWithoutExprType *New =
1415 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1416 ArySize, ASM, EltTypeQuals);
1417 Types.push_back(New);
1418 return QualType(New, 0);
1419}
1420
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001421/// getVariableArrayType - Returns a non-unique reference to the type for a
1422/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001423QualType ASTContext::getVariableArrayType(QualType EltTy,
1424 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001425 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001426 unsigned EltTypeQuals,
1427 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001428 // Since we don't unique expressions, it isn't possible to unique VLA's
1429 // that have an expression provided for their size.
1430
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001431 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001432 new(*this,8)VariableArrayType(EltTy, QualType(),
1433 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001434
1435 VariableArrayTypes.push_back(New);
1436 Types.push_back(New);
1437 return QualType(New, 0);
1438}
1439
Douglas Gregor898574e2008-12-05 23:32:09 +00001440/// getDependentSizedArrayType - Returns a non-unique reference to
1441/// the type for a dependently-sized array of the specified element
1442/// type. FIXME: We will need these to be uniqued, or at least
1443/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001444QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1445 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001446 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001447 unsigned EltTypeQuals,
1448 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001449 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1450 "Size must be type- or value-dependent!");
1451
1452 // Since we don't unique expressions, it isn't possible to unique
1453 // dependently-sized array types.
1454
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001455 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001456 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1457 NumElts, ASM, EltTypeQuals,
1458 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001459
1460 DependentSizedArrayTypes.push_back(New);
1461 Types.push_back(New);
1462 return QualType(New, 0);
1463}
1464
Eli Friedmanc5773c42008-02-15 18:16:39 +00001465QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1466 ArrayType::ArraySizeModifier ASM,
1467 unsigned EltTypeQuals) {
1468 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001469 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001470
1471 void *InsertPos = 0;
1472 if (IncompleteArrayType *ATP =
1473 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1474 return QualType(ATP, 0);
1475
1476 // If the element type isn't canonical, this won't be a canonical type
1477 // either, so fill in the canonical type field.
1478 QualType Canonical;
1479
1480 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001481 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001482 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001483
1484 // Get the new insert position for the node we care about.
1485 IncompleteArrayType *NewIP =
1486 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001487 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001488 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001489
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001490 IncompleteArrayType *New
1491 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1492 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001493
1494 IncompleteArrayTypes.InsertNode(New, InsertPos);
1495 Types.push_back(New);
1496 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001497}
1498
Steve Naroff73322922007-07-18 18:00:27 +00001499/// getVectorType - Return the unique reference to a vector type of
1500/// the specified element type and size. VectorType must be a built-in type.
1501QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 BuiltinType *baseType;
1503
Chris Lattnerf52ab252008-04-06 22:59:24 +00001504 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001505 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001506
1507 // Check if we've already instantiated a vector of this type.
1508 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001509 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 void *InsertPos = 0;
1511 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1512 return QualType(VTP, 0);
1513
1514 // If the element type isn't canonical, this won't be a canonical type either,
1515 // so fill in the canonical type field.
1516 QualType Canonical;
1517 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001518 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001519
1520 // Get the new insert position for the node we care about.
1521 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001522 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
Steve Narofff83820b2009-01-27 22:08:43 +00001524 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 VectorTypes.InsertNode(New, InsertPos);
1526 Types.push_back(New);
1527 return QualType(New, 0);
1528}
1529
Nate Begeman213541a2008-04-18 23:10:10 +00001530/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001531/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001532QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001533 BuiltinType *baseType;
1534
Chris Lattnerf52ab252008-04-06 22:59:24 +00001535 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001536 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001537
1538 // Check if we've already instantiated a vector of this type.
1539 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001540 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001541 void *InsertPos = 0;
1542 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1543 return QualType(VTP, 0);
1544
1545 // If the element type isn't canonical, this won't be a canonical type either,
1546 // so fill in the canonical type field.
1547 QualType Canonical;
1548 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001549 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001550
1551 // Get the new insert position for the node we care about.
1552 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001553 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001554 }
Steve Narofff83820b2009-01-27 22:08:43 +00001555 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001556 VectorTypes.InsertNode(New, InsertPos);
1557 Types.push_back(New);
1558 return QualType(New, 0);
1559}
1560
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001561QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1562 Expr *SizeExpr,
1563 SourceLocation AttrLoc) {
1564 DependentSizedExtVectorType *New =
1565 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1566 SizeExpr, AttrLoc);
1567
1568 DependentSizedExtVectorTypes.push_back(New);
1569 Types.push_back(New);
1570 return QualType(New, 0);
1571}
1572
Douglas Gregor72564e72009-02-26 23:50:07 +00001573/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001574///
Douglas Gregor72564e72009-02-26 23:50:07 +00001575QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Unique functions, to guarantee there is only one function of a particular
1577 // structure.
1578 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001579 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580
1581 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001582 if (FunctionNoProtoType *FT =
1583 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 return QualType(FT, 0);
1585
1586 QualType Canonical;
1587 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001588 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001589
1590 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001591 FunctionNoProtoType *NewIP =
1592 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001593 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
1595
Douglas Gregor72564e72009-02-26 23:50:07 +00001596 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001598 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 return QualType(New, 0);
1600}
1601
1602/// getFunctionType - Return a normal function type with a typed argument
1603/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001604QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001605 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001606 unsigned TypeQuals, bool hasExceptionSpec,
1607 bool hasAnyExceptionSpec, unsigned NumExs,
1608 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // Unique functions, to guarantee there is only one function of a particular
1610 // structure.
1611 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001612 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001613 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1614 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001615
1616 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001617 if (FunctionProtoType *FTP =
1618 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001620
1621 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001623 if (hasExceptionSpec)
1624 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1626 if (!ArgArray[i]->isCanonical())
1627 isCanonical = false;
1628
1629 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001630 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 QualType Canonical;
1632 if (!isCanonical) {
1633 llvm::SmallVector<QualType, 16> CanonicalArgs;
1634 CanonicalArgs.reserve(NumArgs);
1635 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001636 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001637
Chris Lattnerf52ab252008-04-06 22:59:24 +00001638 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001639 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001640 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001641
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001643 FunctionProtoType *NewIP =
1644 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001645 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001647
Douglas Gregor72564e72009-02-26 23:50:07 +00001648 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001649 // for two variable size arrays (for parameter and exception types) at the
1650 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001651 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001652 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1653 NumArgs*sizeof(QualType) +
1654 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001655 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001656 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1657 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001659 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 return QualType(FTP, 0);
1661}
1662
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001663/// getTypeDeclType - Return the unique reference to the type for the
1664/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001665QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001666 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001667 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1668
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001669 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001670 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001671 else if (isa<TemplateTypeParmDecl>(Decl)) {
1672 assert(false && "Template type parameter types are always available.");
1673 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001674 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001675
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001676 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001677 if (PrevDecl)
1678 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001679 else
1680 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001681 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001682 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1683 if (PrevDecl)
1684 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001685 else
1686 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001687 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001688 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001689 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001690
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001691 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001692 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001693}
1694
Reid Spencer5f016e22007-07-11 17:01:13 +00001695/// getTypedefType - Return the unique reference to the type for the
1696/// specified typename decl.
1697QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1698 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1699
Chris Lattnerf52ab252008-04-06 22:59:24 +00001700 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001701 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 Types.push_back(Decl->TypeForDecl);
1703 return QualType(Decl->TypeForDecl, 0);
1704}
1705
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001706/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001707/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001708QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001709 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1710
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001711 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1712 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001713 Types.push_back(Decl->TypeForDecl);
1714 return QualType(Decl->TypeForDecl, 0);
1715}
1716
Douglas Gregorfab9d672009-02-05 23:33:38 +00001717/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001718/// parameter or parameter pack with the given depth, index, and (optionally)
1719/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001720QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001721 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001722 IdentifierInfo *Name) {
1723 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001724 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001725 void *InsertPos = 0;
1726 TemplateTypeParmType *TypeParm
1727 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1728
1729 if (TypeParm)
1730 return QualType(TypeParm, 0);
1731
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001732 if (Name) {
1733 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1734 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1735 Name, Canon);
1736 } else
1737 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001738
1739 Types.push_back(TypeParm);
1740 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1741
1742 return QualType(TypeParm, 0);
1743}
1744
Douglas Gregor55f6b142009-02-09 18:46:07 +00001745QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001746ASTContext::getTemplateSpecializationType(TemplateName Template,
1747 const TemplateArgument *Args,
1748 unsigned NumArgs,
1749 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001750 if (!Canon.isNull())
1751 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001752
Douglas Gregor55f6b142009-02-09 18:46:07 +00001753 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001754 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001755
Douglas Gregor55f6b142009-02-09 18:46:07 +00001756 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001757 TemplateSpecializationType *Spec
1758 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001759
1760 if (Spec)
1761 return QualType(Spec, 0);
1762
Douglas Gregor7532dc62009-03-30 22:58:21 +00001763 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001764 sizeof(TemplateArgument) * NumArgs),
1765 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001766 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001767 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001768 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001769
1770 return QualType(Spec, 0);
1771}
1772
Douglas Gregore4e5b052009-03-19 00:18:19 +00001773QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001774ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001775 QualType NamedType) {
1776 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001777 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001778
1779 void *InsertPos = 0;
1780 QualifiedNameType *T
1781 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1782 if (T)
1783 return QualType(T, 0);
1784
Douglas Gregorab452ba2009-03-26 23:50:42 +00001785 T = new (*this) QualifiedNameType(NNS, NamedType,
1786 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001787 Types.push_back(T);
1788 QualifiedNameTypes.InsertNode(T, InsertPos);
1789 return QualType(T, 0);
1790}
1791
Douglas Gregord57959a2009-03-27 23:10:48 +00001792QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1793 const IdentifierInfo *Name,
1794 QualType Canon) {
1795 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1796
1797 if (Canon.isNull()) {
1798 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1799 if (CanonNNS != NNS)
1800 Canon = getTypenameType(CanonNNS, Name);
1801 }
1802
1803 llvm::FoldingSetNodeID ID;
1804 TypenameType::Profile(ID, NNS, Name);
1805
1806 void *InsertPos = 0;
1807 TypenameType *T
1808 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1809 if (T)
1810 return QualType(T, 0);
1811
1812 T = new (*this) TypenameType(NNS, Name, Canon);
1813 Types.push_back(T);
1814 TypenameTypes.InsertNode(T, InsertPos);
1815 return QualType(T, 0);
1816}
1817
Douglas Gregor17343172009-04-01 00:28:59 +00001818QualType
1819ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1820 const TemplateSpecializationType *TemplateId,
1821 QualType Canon) {
1822 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1823
1824 if (Canon.isNull()) {
1825 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1826 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1827 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1828 const TemplateSpecializationType *CanonTemplateId
1829 = CanonType->getAsTemplateSpecializationType();
1830 assert(CanonTemplateId &&
1831 "Canonical type must also be a template specialization type");
1832 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1833 }
1834 }
1835
1836 llvm::FoldingSetNodeID ID;
1837 TypenameType::Profile(ID, NNS, TemplateId);
1838
1839 void *InsertPos = 0;
1840 TypenameType *T
1841 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1842 if (T)
1843 return QualType(T, 0);
1844
1845 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1846 Types.push_back(T);
1847 TypenameTypes.InsertNode(T, InsertPos);
1848 return QualType(T, 0);
1849}
1850
Chris Lattner88cb27a2008-04-07 04:56:42 +00001851/// CmpProtocolNames - Comparison predicate for sorting protocols
1852/// alphabetically.
1853static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1854 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001855 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001856}
1857
1858static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1859 unsigned &NumProtocols) {
1860 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1861
1862 // Sort protocols, keyed by name.
1863 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1864
1865 // Remove duplicates.
1866 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1867 NumProtocols = ProtocolsEnd-Protocols;
1868}
1869
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001870/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1871/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001872QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001873 ObjCProtocolDecl **Protocols,
1874 unsigned NumProtocols) {
Steve Naroff14108da2009-07-10 23:34:53 +00001875 if (InterfaceT.isNull())
Steve Naroffde2e22d2009-07-15 18:40:39 +00001876 InterfaceT = ObjCBuiltinIdTy;
Steve Naroff14108da2009-07-10 23:34:53 +00001877
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001878 // Sort the protocol list alphabetically to canonicalize it.
1879 if (NumProtocols)
1880 SortAndUniqueProtocols(Protocols, NumProtocols);
1881
1882 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001883 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001884
1885 void *InsertPos = 0;
1886 if (ObjCObjectPointerType *QT =
1887 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1888 return QualType(QT, 0);
1889
1890 // No Match;
1891 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001892 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001893
1894 Types.push_back(QType);
1895 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1896 return QualType(QType, 0);
1897}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001898
Chris Lattner065f0d72008-04-07 04:44:08 +00001899/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1900/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001901QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1902 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001903 // Sort the protocol list alphabetically to canonicalize it.
1904 SortAndUniqueProtocols(Protocols, NumProtocols);
1905
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001906 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001907 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001908
1909 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 if (ObjCQualifiedInterfaceType *QT =
1911 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001912 return QualType(QT, 0);
1913
1914 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001915 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001916 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001917
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001918 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001919 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001920 return QualType(QType, 0);
1921}
1922
Douglas Gregor72564e72009-02-26 23:50:07 +00001923/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1924/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001925/// multiple declarations that refer to "typeof(x)" all contain different
1926/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1927/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001928QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001929 TypeOfExprType *toe;
1930 if (tofExpr->isTypeDependent())
1931 toe = new (*this, 8) TypeOfExprType(tofExpr);
1932 else {
1933 QualType Canonical = getCanonicalType(tofExpr->getType());
1934 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1935 }
Steve Naroff9752f252007-08-01 18:02:17 +00001936 Types.push_back(toe);
1937 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001938}
1939
Steve Naroff9752f252007-08-01 18:02:17 +00001940/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1941/// TypeOfType AST's. The only motivation to unique these nodes would be
1942/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1943/// an issue. This doesn't effect the type checker, since it operates
1944/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001945QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001946 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001947 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001948 Types.push_back(tot);
1949 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001950}
1951
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001952/// getDecltypeForExpr - Given an expr, will return the decltype for that
1953/// expression, according to the rules in C++0x [dcl.type.simple]p4
1954static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001955 if (e->isTypeDependent())
1956 return Context.DependentTy;
1957
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001958 // If e is an id expression or a class member access, decltype(e) is defined
1959 // as the type of the entity named by e.
1960 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1961 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1962 return VD->getType();
1963 }
1964 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1965 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1966 return FD->getType();
1967 }
1968 // If e is a function call or an invocation of an overloaded operator,
1969 // (parentheses around e are ignored), decltype(e) is defined as the
1970 // return type of that function.
1971 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1972 return CE->getCallReturnType();
1973
1974 QualType T = e->getType();
1975
1976 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1977 // defined as T&, otherwise decltype(e) is defined as T.
1978 if (e->isLvalue(Context) == Expr::LV_Valid)
1979 T = Context.getLValueReferenceType(T);
1980
1981 return T;
1982}
1983
Anders Carlsson395b4752009-06-24 19:06:50 +00001984/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1985/// DecltypeType AST's. The only motivation to unique these nodes would be
1986/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1987/// an issue. This doesn't effect the type checker, since it operates
1988/// on canonical type's (which are always unique).
1989QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001990 DecltypeType *dt;
1991 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson563a03b2009-07-10 19:20:26 +00001992 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregordd0257c2009-07-08 00:03:05 +00001993 else {
1994 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00001995 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00001996 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001997 Types.push_back(dt);
1998 return QualType(dt, 0);
1999}
2000
Reid Spencer5f016e22007-07-11 17:01:13 +00002001/// getTagDeclType - Return the unique reference to the type for the
2002/// specified TagDecl (struct/union/class/enum) decl.
2003QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002004 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002005 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002006}
2007
2008/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2009/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2010/// needs to agree with the definition in <stddef.h>.
2011QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002012 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002013}
2014
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002015/// getSignedWCharType - Return the type of "signed wchar_t".
2016/// Used when in C++, as a GCC extension.
2017QualType ASTContext::getSignedWCharType() const {
2018 // FIXME: derive from "Target" ?
2019 return WCharTy;
2020}
2021
2022/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2023/// Used when in C++, as a GCC extension.
2024QualType ASTContext::getUnsignedWCharType() const {
2025 // FIXME: derive from "Target" ?
2026 return UnsignedIntTy;
2027}
2028
Chris Lattner8b9023b2007-07-13 03:05:23 +00002029/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2030/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2031QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002032 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002033}
2034
Chris Lattnere6327742008-04-02 05:18:44 +00002035//===----------------------------------------------------------------------===//
2036// Type Operators
2037//===----------------------------------------------------------------------===//
2038
Chris Lattner77c96472008-04-06 22:41:35 +00002039/// getCanonicalType - Return the canonical (structural) type corresponding to
2040/// the specified potentially non-canonical type. The non-canonical version
2041/// of a type may have many "decorated" versions of types. Decorators can
2042/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2043/// to be free of any of these, allowing two canonical types to be compared
2044/// for exact equality with a simple pointer comparison.
2045QualType ASTContext::getCanonicalType(QualType T) {
2046 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002047
2048 // If the result has type qualifiers, make sure to canonicalize them as well.
2049 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2050 if (TypeQuals == 0) return CanType;
2051
2052 // If the type qualifiers are on an array type, get the canonical type of the
2053 // array with the qualifiers applied to the element type.
2054 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2055 if (!AT)
2056 return CanType.getQualifiedType(TypeQuals);
2057
2058 // Get the canonical version of the element with the extra qualifiers on it.
2059 // This can recursively sink qualifiers through multiple levels of arrays.
2060 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2061 NewEltTy = getCanonicalType(NewEltTy);
2062
2063 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2064 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2065 CAT->getIndexTypeQualifier());
2066 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2067 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2068 IAT->getIndexTypeQualifier());
2069
Douglas Gregor898574e2008-12-05 23:32:09 +00002070 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002071 return getDependentSizedArrayType(NewEltTy,
2072 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002073 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002074 DSAT->getIndexTypeQualifier(),
2075 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002076
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002077 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002078 return getVariableArrayType(NewEltTy,
2079 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002080 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002081 VAT->getIndexTypeQualifier(),
2082 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002083}
2084
Douglas Gregor7da97d02009-05-10 22:57:19 +00002085Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00002086 if (!D)
2087 return 0;
2088
Douglas Gregor7da97d02009-05-10 22:57:19 +00002089 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2090 QualType T = getTagDeclType(Tag);
2091 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2092 ->getDecl());
2093 }
2094
2095 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2096 while (Template->getPreviousDeclaration())
2097 Template = Template->getPreviousDeclaration();
2098 return Template;
2099 }
2100
2101 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2102 while (Function->getPreviousDeclaration())
2103 Function = Function->getPreviousDeclaration();
2104 return const_cast<FunctionDecl *>(Function);
2105 }
2106
Douglas Gregor127102b2009-06-29 20:59:39 +00002107 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2108 while (FunTmpl->getPreviousDeclaration())
2109 FunTmpl = FunTmpl->getPreviousDeclaration();
2110 return FunTmpl;
2111 }
2112
Douglas Gregor7da97d02009-05-10 22:57:19 +00002113 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2114 while (Var->getPreviousDeclaration())
2115 Var = Var->getPreviousDeclaration();
2116 return const_cast<VarDecl *>(Var);
2117 }
2118
2119 return D;
2120}
2121
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002122TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2123 // If this template name refers to a template, the canonical
2124 // template name merely stores the template itself.
2125 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002126 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002127
2128 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2129 assert(DTN && "Non-dependent template names must refer to template decls.");
2130 return DTN->CanonicalTemplateName;
2131}
2132
Douglas Gregord57959a2009-03-27 23:10:48 +00002133NestedNameSpecifier *
2134ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2135 if (!NNS)
2136 return 0;
2137
2138 switch (NNS->getKind()) {
2139 case NestedNameSpecifier::Identifier:
2140 // Canonicalize the prefix but keep the identifier the same.
2141 return NestedNameSpecifier::Create(*this,
2142 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2143 NNS->getAsIdentifier());
2144
2145 case NestedNameSpecifier::Namespace:
2146 // A namespace is canonical; build a nested-name-specifier with
2147 // this namespace and no prefix.
2148 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2149
2150 case NestedNameSpecifier::TypeSpec:
2151 case NestedNameSpecifier::TypeSpecWithTemplate: {
2152 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2153 NestedNameSpecifier *Prefix = 0;
2154
2155 // FIXME: This isn't the right check!
2156 if (T->isDependentType())
2157 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2158
2159 return NestedNameSpecifier::Create(*this, Prefix,
2160 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2161 T.getTypePtr());
2162 }
2163
2164 case NestedNameSpecifier::Global:
2165 // The global specifier is canonical and unique.
2166 return NNS;
2167 }
2168
2169 // Required to silence a GCC warning
2170 return 0;
2171}
2172
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002173
2174const ArrayType *ASTContext::getAsArrayType(QualType T) {
2175 // Handle the non-qualified case efficiently.
2176 if (T.getCVRQualifiers() == 0) {
2177 // Handle the common positive case fast.
2178 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2179 return AT;
2180 }
2181
2182 // Handle the common negative case fast, ignoring CVR qualifiers.
2183 QualType CType = T->getCanonicalTypeInternal();
2184
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002185 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002186 // test.
2187 if (!isa<ArrayType>(CType) &&
2188 !isa<ArrayType>(CType.getUnqualifiedType()))
2189 return 0;
2190
2191 // Apply any CVR qualifiers from the array type to the element type. This
2192 // implements C99 6.7.3p8: "If the specification of an array type includes
2193 // any type qualifiers, the element type is so qualified, not the array type."
2194
2195 // If we get here, we either have type qualifiers on the type, or we have
2196 // sugar such as a typedef in the way. If we have type qualifiers on the type
2197 // we must propagate them down into the elemeng type.
2198 unsigned CVRQuals = T.getCVRQualifiers();
2199 unsigned AddrSpace = 0;
2200 Type *Ty = T.getTypePtr();
2201
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002202 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002203 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002204 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2205 AddrSpace = EXTQT->getAddressSpace();
2206 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002207 } else {
2208 T = Ty->getDesugaredType();
2209 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2210 break;
2211 CVRQuals |= T.getCVRQualifiers();
2212 Ty = T.getTypePtr();
2213 }
2214 }
2215
2216 // If we have a simple case, just return now.
2217 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2218 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2219 return ATy;
2220
2221 // Otherwise, we have an array and we have qualifiers on it. Push the
2222 // qualifiers into the array element type and return a new array type.
2223 // Get the canonical version of the element with the extra qualifiers on it.
2224 // This can recursively sink qualifiers through multiple levels of arrays.
2225 QualType NewEltTy = ATy->getElementType();
2226 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002227 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002228 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2229
2230 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2231 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2232 CAT->getSizeModifier(),
2233 CAT->getIndexTypeQualifier()));
2234 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2235 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2236 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002237 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002238
Douglas Gregor898574e2008-12-05 23:32:09 +00002239 if (const DependentSizedArrayType *DSAT
2240 = dyn_cast<DependentSizedArrayType>(ATy))
2241 return cast<ArrayType>(
2242 getDependentSizedArrayType(NewEltTy,
2243 DSAT->getSizeExpr(),
2244 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002245 DSAT->getIndexTypeQualifier(),
2246 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002247
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002248 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002249 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2250 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002251 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002252 VAT->getIndexTypeQualifier(),
2253 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002254}
2255
2256
Chris Lattnere6327742008-04-02 05:18:44 +00002257/// getArrayDecayedType - Return the properly qualified result of decaying the
2258/// specified array type to a pointer. This operation is non-trivial when
2259/// handling typedefs etc. The canonical type of "T" must be an array type,
2260/// this returns a pointer to a properly qualified element of the array.
2261///
2262/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2263QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002264 // Get the element type with 'getAsArrayType' so that we don't lose any
2265 // typedefs in the element type of the array. This also handles propagation
2266 // of type qualifiers from the array type into the element type if present
2267 // (C99 6.7.3p8).
2268 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2269 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002270
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002271 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002272
2273 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002274 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002275}
2276
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002277QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002278 QualType ElemTy = VAT->getElementType();
2279
2280 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2281 return getBaseElementType(VAT);
2282
2283 return ElemTy;
2284}
2285
Reid Spencer5f016e22007-07-11 17:01:13 +00002286/// getFloatingRank - Return a relative rank for floating point types.
2287/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002288static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002289 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002291
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002292 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002293 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002294 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 case BuiltinType::Float: return FloatRank;
2296 case BuiltinType::Double: return DoubleRank;
2297 case BuiltinType::LongDouble: return LongDoubleRank;
2298 }
2299}
2300
Steve Naroff716c7302007-08-27 01:41:48 +00002301/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2302/// point or a complex type (based on typeDomain/typeSize).
2303/// 'typeDomain' is a real floating point or complex type.
2304/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002305QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2306 QualType Domain) const {
2307 FloatingRank EltRank = getFloatingRank(Size);
2308 if (Domain->isComplexType()) {
2309 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002310 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002311 case FloatRank: return FloatComplexTy;
2312 case DoubleRank: return DoubleComplexTy;
2313 case LongDoubleRank: return LongDoubleComplexTy;
2314 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 }
Chris Lattner1361b112008-04-06 23:58:54 +00002316
2317 assert(Domain->isRealFloatingType() && "Unknown domain!");
2318 switch (EltRank) {
2319 default: assert(0 && "getFloatingRank(): illegal value for rank");
2320 case FloatRank: return FloatTy;
2321 case DoubleRank: return DoubleTy;
2322 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002323 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002324}
2325
Chris Lattner7cfeb082008-04-06 23:55:33 +00002326/// getFloatingTypeOrder - Compare the rank of the two specified floating
2327/// point types, ignoring the domain of the type (i.e. 'double' ==
2328/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2329/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002330int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2331 FloatingRank LHSR = getFloatingRank(LHS);
2332 FloatingRank RHSR = getFloatingRank(RHS);
2333
2334 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002335 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002336 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002337 return 1;
2338 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002339}
2340
Chris Lattnerf52ab252008-04-06 22:59:24 +00002341/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2342/// routine will assert if passed a built-in type that isn't an integer or enum,
2343/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002344unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002345 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002346 if (EnumType* ET = dyn_cast<EnumType>(T))
2347 T = ET->getDecl()->getIntegerType().getTypePtr();
2348
Eli Friedmana3426752009-07-05 23:44:27 +00002349 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2350 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2351
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002352 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2353 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2354
2355 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2356 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2357
Eli Friedmanf98aba32009-02-13 02:31:07 +00002358 // There are two things which impact the integer rank: the width, and
2359 // the ordering of builtins. The builtin ordering is encoded in the
2360 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002361 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002362 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002363
Chris Lattnerf52ab252008-04-06 22:59:24 +00002364 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002365 default: assert(0 && "getIntegerRank(): not a built-in integer");
2366 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002367 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002368 case BuiltinType::Char_S:
2369 case BuiltinType::Char_U:
2370 case BuiltinType::SChar:
2371 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002372 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002373 case BuiltinType::Short:
2374 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002375 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002376 case BuiltinType::Int:
2377 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002378 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002379 case BuiltinType::Long:
2380 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002381 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002382 case BuiltinType::LongLong:
2383 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002384 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002385 case BuiltinType::Int128:
2386 case BuiltinType::UInt128:
2387 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002388 }
2389}
2390
Chris Lattner7cfeb082008-04-06 23:55:33 +00002391/// getIntegerTypeOrder - Returns the highest ranked integer type:
2392/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2393/// LHS < RHS, return -1.
2394int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002395 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2396 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002397 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002398
Chris Lattnerf52ab252008-04-06 22:59:24 +00002399 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2400 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002401
Chris Lattner7cfeb082008-04-06 23:55:33 +00002402 unsigned LHSRank = getIntegerRank(LHSC);
2403 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002404
Chris Lattner7cfeb082008-04-06 23:55:33 +00002405 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2406 if (LHSRank == RHSRank) return 0;
2407 return LHSRank > RHSRank ? 1 : -1;
2408 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002409
Chris Lattner7cfeb082008-04-06 23:55:33 +00002410 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2411 if (LHSUnsigned) {
2412 // If the unsigned [LHS] type is larger, return it.
2413 if (LHSRank >= RHSRank)
2414 return 1;
2415
2416 // If the signed type can represent all values of the unsigned type, it
2417 // wins. Because we are dealing with 2's complement and types that are
2418 // powers of two larger than each other, this is always safe.
2419 return -1;
2420 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002421
Chris Lattner7cfeb082008-04-06 23:55:33 +00002422 // If the unsigned [RHS] type is larger, return it.
2423 if (RHSRank >= LHSRank)
2424 return -1;
2425
2426 // If the signed type can represent all values of the unsigned type, it
2427 // wins. Because we are dealing with 2's complement and types that are
2428 // powers of two larger than each other, this is always safe.
2429 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002430}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002431
2432// getCFConstantStringType - Return the type used for constant CFStrings.
2433QualType ASTContext::getCFConstantStringType() {
2434 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002435 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002436 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002437 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002438 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002439
2440 // const int *isa;
2441 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002442 // int flags;
2443 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002444 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002445 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002446 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002447 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002448
Anders Carlsson71993dd2007-08-17 05:31:46 +00002449 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002450 for (unsigned i = 0; i < 4; ++i) {
2451 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2452 SourceLocation(), 0,
2453 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002454 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002455 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002456 }
2457
2458 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002459 }
2460
2461 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002462}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002463
Douglas Gregor319ac892009-04-23 22:29:11 +00002464void ASTContext::setCFConstantStringType(QualType T) {
2465 const RecordType *Rec = T->getAsRecordType();
2466 assert(Rec && "Invalid CFConstantStringType");
2467 CFConstantStringTypeDecl = Rec->getDecl();
2468}
2469
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002470QualType ASTContext::getObjCFastEnumerationStateType()
2471{
2472 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002473 ObjCFastEnumerationStateTypeDecl =
2474 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2475 &Idents.get("__objcFastEnumerationState"));
2476
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002477 QualType FieldTypes[] = {
2478 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002479 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002480 getPointerType(UnsignedLongTy),
2481 getConstantArrayType(UnsignedLongTy,
2482 llvm::APInt(32, 5), ArrayType::Normal, 0)
2483 };
2484
Douglas Gregor44b43212008-12-11 16:49:14 +00002485 for (size_t i = 0; i < 4; ++i) {
2486 FieldDecl *Field = FieldDecl::Create(*this,
2487 ObjCFastEnumerationStateTypeDecl,
2488 SourceLocation(), 0,
2489 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002490 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002491 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002492 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002493
Douglas Gregor44b43212008-12-11 16:49:14 +00002494 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002495 }
2496
2497 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2498}
2499
Douglas Gregor319ac892009-04-23 22:29:11 +00002500void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2501 const RecordType *Rec = T->getAsRecordType();
2502 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2503 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2504}
2505
Anders Carlssone8c49532007-10-29 06:33:42 +00002506// This returns true if a type has been typedefed to BOOL:
2507// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002508static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002509 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002510 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2511 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002512
2513 return false;
2514}
2515
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002516/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002517/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002519 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002520
2521 // Make all integer and enum types at least as large as an int
2522 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002523 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002524 // Treat arrays as pointers, since that's how they're passed in.
2525 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002526 sz = getTypeSize(VoidPtrTy);
2527 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002528}
2529
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002530/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002531/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002532void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002533 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002534 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002535 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002536 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002537 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002538 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002539 // Compute size of all parameters.
2540 // Start with computing size of a pointer in number of bytes.
2541 // FIXME: There might(should) be a better way of doing this computation!
2542 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002543 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002544 // The first two arguments (self and _cmd) are pointers; account for
2545 // their size.
2546 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002547 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2548 E = Decl->param_end(); PI != E; ++PI) {
2549 QualType PType = (*PI)->getType();
2550 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002551 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002552 ParmOffset += sz;
2553 }
2554 S += llvm::utostr(ParmOffset);
2555 S += "@0:";
2556 S += llvm::utostr(PtrSize);
2557
2558 // Argument types.
2559 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002560 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2561 E = Decl->param_end(); PI != E; ++PI) {
2562 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002563 QualType PType = PVDecl->getOriginalType();
2564 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002565 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2566 // Use array's original type only if it has known number of
2567 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002568 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002569 PType = PVDecl->getType();
2570 } else if (PType->isFunctionType())
2571 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002572 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002573 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002574 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002575 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002576 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002577 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002578 }
2579}
2580
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002581/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002582/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002583/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2584/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002585/// Property attributes are stored as a comma-delimited C string. The simple
2586/// attributes readonly and bycopy are encoded as single characters. The
2587/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2588/// encoded as single characters, followed by an identifier. Property types
2589/// are also encoded as a parametrized attribute. The characters used to encode
2590/// these attributes are defined by the following enumeration:
2591/// @code
2592/// enum PropertyAttributes {
2593/// kPropertyReadOnly = 'R', // property is read-only.
2594/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2595/// kPropertyByref = '&', // property is a reference to the value last assigned
2596/// kPropertyDynamic = 'D', // property is dynamic
2597/// kPropertyGetter = 'G', // followed by getter selector name
2598/// kPropertySetter = 'S', // followed by setter selector name
2599/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2600/// kPropertyType = 't' // followed by old-style type encoding.
2601/// kPropertyWeak = 'W' // 'weak' property
2602/// kPropertyStrong = 'P' // property GC'able
2603/// kPropertyNonAtomic = 'N' // property non-atomic
2604/// };
2605/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002606void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2607 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002608 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002609 // Collect information from the property implementation decl(s).
2610 bool Dynamic = false;
2611 ObjCPropertyImplDecl *SynthesizePID = 0;
2612
2613 // FIXME: Duplicated code due to poor abstraction.
2614 if (Container) {
2615 if (const ObjCCategoryImplDecl *CID =
2616 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2617 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002618 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002619 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002620 ObjCPropertyImplDecl *PID = *i;
2621 if (PID->getPropertyDecl() == PD) {
2622 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2623 Dynamic = true;
2624 } else {
2625 SynthesizePID = PID;
2626 }
2627 }
2628 }
2629 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002630 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002631 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002632 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002633 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002634 ObjCPropertyImplDecl *PID = *i;
2635 if (PID->getPropertyDecl() == PD) {
2636 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2637 Dynamic = true;
2638 } else {
2639 SynthesizePID = PID;
2640 }
2641 }
2642 }
2643 }
2644 }
2645
2646 // FIXME: This is not very efficient.
2647 S = "T";
2648
2649 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002650 // GCC has some special rules regarding encoding of properties which
2651 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002652 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002653 true /* outermost type */,
2654 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002655
2656 if (PD->isReadOnly()) {
2657 S += ",R";
2658 } else {
2659 switch (PD->getSetterKind()) {
2660 case ObjCPropertyDecl::Assign: break;
2661 case ObjCPropertyDecl::Copy: S += ",C"; break;
2662 case ObjCPropertyDecl::Retain: S += ",&"; break;
2663 }
2664 }
2665
2666 // It really isn't clear at all what this means, since properties
2667 // are "dynamic by default".
2668 if (Dynamic)
2669 S += ",D";
2670
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002671 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2672 S += ",N";
2673
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002674 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2675 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002676 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002677 }
2678
2679 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2680 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002681 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002682 }
2683
2684 if (SynthesizePID) {
2685 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2686 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002687 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002688 }
2689
2690 // FIXME: OBJCGC: weak & strong
2691}
2692
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002693/// getLegacyIntegralTypeEncoding -
2694/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002695/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002696/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2697///
2698void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2699 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2700 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002701 if (BT->getKind() == BuiltinType::ULong &&
2702 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002703 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002704 else
2705 if (BT->getKind() == BuiltinType::Long &&
2706 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002707 PointeeTy = IntTy;
2708 }
2709 }
2710}
2711
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002712void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002713 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002714 // We follow the behavior of gcc, expanding structures which are
2715 // directly pointed to, and expanding embedded structures. Note that
2716 // these rules are sufficient to prevent recursive encoding of the
2717 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002718 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2719 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002720}
2721
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002722static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002723 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002724 const Expr *E = FD->getBitWidth();
2725 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2726 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002727 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002728 S += 'b';
2729 S += llvm::utostr(N);
2730}
2731
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002732void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2733 bool ExpandPointedToStructures,
2734 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002735 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002736 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002737 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002738 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002739 if (FD && FD->isBitField())
2740 return EncodeBitField(this, S, FD);
2741 char encoding;
2742 switch (BT->getKind()) {
2743 default: assert(0 && "Unhandled builtin type kind");
2744 case BuiltinType::Void: encoding = 'v'; break;
2745 case BuiltinType::Bool: encoding = 'B'; break;
2746 case BuiltinType::Char_U:
2747 case BuiltinType::UChar: encoding = 'C'; break;
2748 case BuiltinType::UShort: encoding = 'S'; break;
2749 case BuiltinType::UInt: encoding = 'I'; break;
2750 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002751 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002752 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002753 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002754 case BuiltinType::UInt128: encoding = 'T'; break;
2755 case BuiltinType::ULongLong: encoding = 'Q'; break;
2756 case BuiltinType::Char_S:
2757 case BuiltinType::SChar: encoding = 'c'; break;
2758 case BuiltinType::Short: encoding = 's'; break;
2759 case BuiltinType::Int: encoding = 'i'; break;
2760 case BuiltinType::Long:
2761 encoding =
2762 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2763 break;
2764 case BuiltinType::LongLong: encoding = 'q'; break;
2765 case BuiltinType::Int128: encoding = 't'; break;
2766 case BuiltinType::Float: encoding = 'f'; break;
2767 case BuiltinType::Double: encoding = 'd'; break;
2768 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002769 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002770
2771 S += encoding;
2772 return;
2773 }
2774
2775 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002776 S += 'j';
2777 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2778 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002779 return;
2780 }
2781
2782 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002783 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002784 bool isReadOnly = false;
2785 // For historical/compatibility reasons, the read-only qualifier of the
2786 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2787 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2788 // Also, do not emit the 'r' for anything but the outermost type!
2789 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2790 if (OutermostType && T.isConstQualified()) {
2791 isReadOnly = true;
2792 S += 'r';
2793 }
2794 }
2795 else if (OutermostType) {
2796 QualType P = PointeeTy;
2797 while (P->getAsPointerType())
2798 P = P->getAsPointerType()->getPointeeType();
2799 if (P.isConstQualified()) {
2800 isReadOnly = true;
2801 S += 'r';
2802 }
2803 }
2804 if (isReadOnly) {
2805 // Another legacy compatibility encoding. Some ObjC qualifier and type
2806 // combinations need to be rearranged.
2807 // Rewrite "in const" from "nr" to "rn"
2808 const char * s = S.c_str();
2809 int len = S.length();
2810 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2811 std::string replace = "rn";
2812 S.replace(S.end()-2, S.end(), replace);
2813 }
2814 }
Steve Naroff14108da2009-07-10 23:34:53 +00002815 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002816 S += ':';
2817 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002818 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002819
2820 if (PointeeTy->isCharType()) {
2821 // char pointer types should be encoded as '*' unless it is a
2822 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002823 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002824 S += '*';
2825 return;
2826 }
2827 }
2828
2829 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002830 getLegacyIntegralTypeEncoding(PointeeTy);
2831
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002832 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002833 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002834 return;
2835 }
2836
2837 if (const ArrayType *AT =
2838 // Ignore type qualifiers etc.
2839 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002840 if (isa<IncompleteArrayType>(AT)) {
2841 // Incomplete arrays are encoded as a pointer to the array element.
2842 S += '^';
2843
2844 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2845 false, ExpandStructures, FD);
2846 } else {
2847 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002848
Anders Carlsson559a8332009-02-22 01:38:57 +00002849 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2850 S += llvm::utostr(CAT->getSize().getZExtValue());
2851 else {
2852 //Variable length arrays are encoded as a regular array with 0 elements.
2853 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2854 S += '0';
2855 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002856
Anders Carlsson559a8332009-02-22 01:38:57 +00002857 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2858 false, ExpandStructures, FD);
2859 S += ']';
2860 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002861 return;
2862 }
2863
2864 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002865 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002866 return;
2867 }
2868
2869 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002870 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002871 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002872 // Anonymous structures print as '?'
2873 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2874 S += II->getName();
2875 } else {
2876 S += '?';
2877 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002878 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002879 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002880 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2881 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002882 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002883 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002884 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002885 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002886 S += '"';
2887 }
2888
2889 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002890 if (Field->isBitField()) {
2891 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2892 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002893 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002894 QualType qt = Field->getType();
2895 getLegacyIntegralTypeEncoding(qt);
2896 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002897 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002898 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002899 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002900 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002901 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002902 return;
2903 }
2904
2905 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002906 if (FD && FD->isBitField())
2907 EncodeBitField(this, S, FD);
2908 else
2909 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002910 return;
2911 }
2912
2913 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002914 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002915 return;
2916 }
2917
2918 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002919 // @encode(class_name)
2920 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2921 S += '{';
2922 const IdentifierInfo *II = OI->getIdentifier();
2923 S += II->getName();
2924 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002925 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002926 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002927 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002928 if (RecFields[i]->isBitField())
2929 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2930 RecFields[i]);
2931 else
2932 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2933 FD);
2934 }
2935 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002936 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002937 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002938
2939 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002940 if (OPT->isObjCIdType()) {
2941 S += '@';
2942 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002943 }
2944
2945 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002946 S += '#';
2947 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002948 }
2949
2950 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002951 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2952 ExpandPointedToStructures,
2953 ExpandStructures, FD);
2954 if (FD || EncodingProperty) {
2955 // Note that we do extended encoding of protocol qualifer list
2956 // Only when doing ivar or property encoding.
2957 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2958 S += '"';
2959 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2960 E = QIDT->qual_end(); I != E; ++I) {
2961 S += '<';
2962 S += (*I)->getNameAsString();
2963 S += '>';
2964 }
2965 S += '"';
2966 }
2967 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002968 }
2969
2970 QualType PointeeTy = OPT->getPointeeType();
2971 if (!EncodingProperty &&
2972 isa<TypedefType>(PointeeTy.getTypePtr())) {
2973 // Another historical/compatibility reason.
2974 // We encode the underlying type which comes out as
2975 // {...};
2976 S += '^';
2977 getObjCEncodingForTypeImpl(PointeeTy, S,
2978 false, ExpandPointedToStructures,
2979 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00002980 return;
2981 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002982
2983 S += '@';
2984 if (FD || EncodingProperty) {
2985 const ObjCInterfaceType *OIT = OPT->getInterfaceType();
2986 ObjCInterfaceDecl *OI = OIT->getDecl();
2987 S += '"';
2988 S += OI->getNameAsCString();
2989 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2990 E = OIT->qual_end(); I != E; ++I) {
2991 S += '<';
2992 S += (*I)->getNameAsString();
2993 S += '>';
2994 }
2995 S += '"';
2996 }
2997 return;
2998 }
2999
3000 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003001}
3002
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003003void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003004 std::string& S) const {
3005 if (QT & Decl::OBJC_TQ_In)
3006 S += 'n';
3007 if (QT & Decl::OBJC_TQ_Inout)
3008 S += 'N';
3009 if (QT & Decl::OBJC_TQ_Out)
3010 S += 'o';
3011 if (QT & Decl::OBJC_TQ_Bycopy)
3012 S += 'O';
3013 if (QT & Decl::OBJC_TQ_Byref)
3014 S += 'R';
3015 if (QT & Decl::OBJC_TQ_Oneway)
3016 S += 'V';
3017}
3018
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003019void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003020 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3021
3022 BuiltinVaListType = T;
3023}
3024
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003025void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003026 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003027}
3028
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003029void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003030 ObjCSelType = T;
3031
3032 const TypedefType *TT = T->getAsTypedefType();
3033 if (!TT)
3034 return;
3035 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003036
3037 // typedef struct objc_selector *SEL;
3038 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003039 if (!ptr)
3040 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003041 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003042 if (!rec)
3043 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003044 SelStructType = rec;
3045}
3046
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003047void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003048 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003049}
3050
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003051void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003052 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003053}
3054
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003055void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3056 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003057 "'NSConstantString' type already set!");
3058
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003059 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003060}
3061
Douglas Gregor7532dc62009-03-30 22:58:21 +00003062/// \brief Retrieve the template name that represents a qualified
3063/// template name such as \c std::vector.
3064TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3065 bool TemplateKeyword,
3066 TemplateDecl *Template) {
3067 llvm::FoldingSetNodeID ID;
3068 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3069
3070 void *InsertPos = 0;
3071 QualifiedTemplateName *QTN =
3072 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3073 if (!QTN) {
3074 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3075 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3076 }
3077
3078 return TemplateName(QTN);
3079}
3080
3081/// \brief Retrieve the template name that represents a dependent
3082/// template name such as \c MetaFun::template apply.
3083TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3084 const IdentifierInfo *Name) {
3085 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3086
3087 llvm::FoldingSetNodeID ID;
3088 DependentTemplateName::Profile(ID, NNS, Name);
3089
3090 void *InsertPos = 0;
3091 DependentTemplateName *QTN =
3092 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3093
3094 if (QTN)
3095 return TemplateName(QTN);
3096
3097 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3098 if (CanonNNS == NNS) {
3099 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3100 } else {
3101 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3102 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3103 }
3104
3105 DependentTemplateNames.InsertNode(QTN, InsertPos);
3106 return TemplateName(QTN);
3107}
3108
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003109/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003110/// TargetInfo, produce the corresponding type. The unsigned @p Type
3111/// is actually a value of type @c TargetInfo::IntType.
3112QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003113 switch (Type) {
3114 case TargetInfo::NoInt: return QualType();
3115 case TargetInfo::SignedShort: return ShortTy;
3116 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3117 case TargetInfo::SignedInt: return IntTy;
3118 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3119 case TargetInfo::SignedLong: return LongTy;
3120 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3121 case TargetInfo::SignedLongLong: return LongLongTy;
3122 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3123 }
3124
3125 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003126 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003127}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003128
3129//===----------------------------------------------------------------------===//
3130// Type Predicates.
3131//===----------------------------------------------------------------------===//
3132
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003133/// isObjCNSObjectType - Return true if this is an NSObject object using
3134/// NSObject attribute on a c-style pointer type.
3135/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003136/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003137///
3138bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3139 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3140 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003141 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003142 return true;
3143 }
3144 return false;
3145}
3146
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003147/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3148/// garbage collection attribute.
3149///
3150QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003151 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003152 if (getLangOptions().ObjC1 &&
3153 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003154 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003155 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003156 // (or pointers to them) be treated as though they were declared
3157 // as __strong.
3158 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003159 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003160 GCAttrs = QualType::Strong;
3161 else if (Ty->isPointerType())
3162 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3163 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003164 // Non-pointers have none gc'able attribute regardless of the attribute
3165 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003166 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003167 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003168 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003169 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003170}
3171
Chris Lattner6ac46a42008-04-07 06:51:04 +00003172//===----------------------------------------------------------------------===//
3173// Type Compatibility Testing
3174//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003175
Chris Lattner6ac46a42008-04-07 06:51:04 +00003176/// areCompatVectorTypes - Return true if the two specified vector types are
3177/// compatible.
3178static bool areCompatVectorTypes(const VectorType *LHS,
3179 const VectorType *RHS) {
3180 assert(LHS->isCanonical() && RHS->isCanonical());
3181 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003182 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003183}
3184
Eli Friedman3d815e72008-08-22 00:56:42 +00003185/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003186/// compatible for assignment from RHS to LHS. This handles validation of any
3187/// protocol qualifiers on the LHS or RHS.
3188///
Steve Naroff14108da2009-07-10 23:34:53 +00003189/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3190bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3191 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003192 // If either type represents the built-in 'id' or 'Class' types, return true.
3193 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003194 return true;
3195
3196 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3197 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroffde2e22d2009-07-15 18:40:39 +00003198 if (!LHS || !RHS) {
3199 // We have qualified builtin types.
3200 // Both the right and left sides have qualifiers.
3201 for (ObjCObjectPointerType::qual_iterator I = LHSOPT->qual_begin(),
3202 E = LHSOPT->qual_end(); I != E; ++I) {
3203 bool RHSImplementsProtocol = false;
3204
3205 // when comparing an id<P> on lhs with a static type on rhs,
3206 // see if static class implements all of id's protocols, directly or
3207 // through its super class and categories.
3208 for (ObjCObjectPointerType::qual_iterator J = RHSOPT->qual_begin(),
3209 E = RHSOPT->qual_end(); J != E; ++J) {
Steve Naroff8f167562009-07-16 16:21:02 +00003210 if ((*J)->lookupProtocolNamed((*I)->getIdentifier())) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003211 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003212 break;
3213 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003214 }
3215 if (!RHSImplementsProtocol)
3216 return false;
3217 }
3218 // The RHS implements all protocols listed on the LHS.
3219 return true;
3220 }
Steve Naroff14108da2009-07-10 23:34:53 +00003221 return canAssignObjCInterfaces(LHS, RHS);
3222}
3223
Eli Friedman3d815e72008-08-22 00:56:42 +00003224bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3225 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003226 // Verify that the base decls are compatible: the RHS must be a subclass of
3227 // the LHS.
3228 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3229 return false;
3230
3231 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3232 // protocol qualified at all, then we are good.
3233 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3234 return true;
3235
3236 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3237 // isn't a superset.
3238 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3239 return true; // FIXME: should return false!
3240
3241 // Finally, we must have two protocol-qualified interfaces.
3242 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3243 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003244
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003245 // All LHS protocols must have a presence on the RHS.
3246 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003247
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003248 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3249 LHSPE = LHSP->qual_end();
3250 LHSPI != LHSPE; LHSPI++) {
3251 bool RHSImplementsProtocol = false;
3252
3253 // If the RHS doesn't implement the protocol on the left, the types
3254 // are incompatible.
3255 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3256 RHSPE = RHSP->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003257 RHSPI != RHSPE; RHSPI++) {
3258 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003259 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003260 break;
3261 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003262 }
3263 // FIXME: For better diagnostics, consider passing back the protocol name.
3264 if (!RHSImplementsProtocol)
3265 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003266 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003267 // The RHS implements all protocols listed on the LHS.
3268 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003269}
3270
Steve Naroff389bf462009-02-12 17:52:19 +00003271bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3272 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003273 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3274 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003275
Steve Naroff14108da2009-07-10 23:34:53 +00003276 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003277 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003278
3279 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3280 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003281}
3282
Steve Naroffec0550f2007-10-15 20:41:53 +00003283/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3284/// both shall have the identically qualified version of a compatible type.
3285/// C99 6.2.7p1: Two types have compatible types if their types are the
3286/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003287bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3288 return !mergeTypes(LHS, RHS).isNull();
3289}
3290
3291QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3292 const FunctionType *lbase = lhs->getAsFunctionType();
3293 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003294 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3295 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003296 bool allLTypes = true;
3297 bool allRTypes = true;
3298
3299 // Check return type
3300 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3301 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003302 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3303 allLTypes = false;
3304 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3305 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003306
3307 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003308 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3309 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003310 unsigned lproto_nargs = lproto->getNumArgs();
3311 unsigned rproto_nargs = rproto->getNumArgs();
3312
3313 // Compatible functions must have the same number of arguments
3314 if (lproto_nargs != rproto_nargs)
3315 return QualType();
3316
3317 // Variadic and non-variadic functions aren't compatible
3318 if (lproto->isVariadic() != rproto->isVariadic())
3319 return QualType();
3320
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003321 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3322 return QualType();
3323
Eli Friedman3d815e72008-08-22 00:56:42 +00003324 // Check argument compatibility
3325 llvm::SmallVector<QualType, 10> types;
3326 for (unsigned i = 0; i < lproto_nargs; i++) {
3327 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3328 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3329 QualType argtype = mergeTypes(largtype, rargtype);
3330 if (argtype.isNull()) return QualType();
3331 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003332 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3333 allLTypes = false;
3334 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3335 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003336 }
3337 if (allLTypes) return lhs;
3338 if (allRTypes) return rhs;
3339 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003340 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003341 }
3342
3343 if (lproto) allRTypes = false;
3344 if (rproto) allLTypes = false;
3345
Douglas Gregor72564e72009-02-26 23:50:07 +00003346 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003347 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003348 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003349 if (proto->isVariadic()) return QualType();
3350 // Check that the types are compatible with the types that
3351 // would result from default argument promotions (C99 6.7.5.3p15).
3352 // The only types actually affected are promotable integer
3353 // types and floats, which would be passed as a different
3354 // type depending on whether the prototype is visible.
3355 unsigned proto_nargs = proto->getNumArgs();
3356 for (unsigned i = 0; i < proto_nargs; ++i) {
3357 QualType argTy = proto->getArgType(i);
3358 if (argTy->isPromotableIntegerType() ||
3359 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3360 return QualType();
3361 }
3362
3363 if (allLTypes) return lhs;
3364 if (allRTypes) return rhs;
3365 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003366 proto->getNumArgs(), lproto->isVariadic(),
3367 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003368 }
3369
3370 if (allLTypes) return lhs;
3371 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003372 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003373}
3374
3375QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003376 // C++ [expr]: If an expression initially has the type "reference to T", the
3377 // type is adjusted to "T" prior to any further analysis, the expression
3378 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003379 // expression is an lvalue unless the reference is an rvalue reference and
3380 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003381 // FIXME: C++ shouldn't be going through here! The rules are different
3382 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003383 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3384 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003385 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003386 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003387 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003388 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003389
Eli Friedman3d815e72008-08-22 00:56:42 +00003390 QualType LHSCan = getCanonicalType(LHS),
3391 RHSCan = getCanonicalType(RHS);
3392
3393 // If two types are identical, they are compatible.
3394 if (LHSCan == RHSCan)
3395 return LHS;
3396
3397 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003398 // Note that we handle extended qualifiers later, in the
3399 // case for ExtQualType.
3400 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003401 return QualType();
3402
Eli Friedman852d63b2009-06-01 01:22:52 +00003403 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3404 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003405
Chris Lattner1adb8832008-01-14 05:45:46 +00003406 // We want to consider the two function types to be the same for these
3407 // comparisons, just force one to the other.
3408 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3409 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003410
Eli Friedman07d25872009-06-02 05:28:56 +00003411 // Strip off objc_gc attributes off the top level so they can be merged.
3412 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003413 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003414 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3415 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003416 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003417 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003418 // __strong attribue is redundant if other decl is an objective-c
3419 // object pointer (or decorated with __strong attribute); otherwise
3420 // issue error.
3421 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3422 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003423 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003424 return QualType();
3425
Eli Friedman07d25872009-06-02 05:28:56 +00003426 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3427 RHS.getCVRQualifiers());
3428 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003429 if (!Result.isNull()) {
3430 if (Result.getObjCGCAttr() == QualType::GCNone)
3431 Result = getObjCGCQualType(Result, GCAttr);
3432 else if (Result.getObjCGCAttr() != GCAttr)
3433 Result = QualType();
3434 }
Eli Friedman07d25872009-06-02 05:28:56 +00003435 return Result;
3436 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003437 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003438 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003439 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3440 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003441 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3442 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003443 // __strong attribue is redundant if other decl is an objective-c
3444 // object pointer (or decorated with __strong attribute); otherwise
3445 // issue error.
3446 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3447 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003448 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003449 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003450
Eli Friedman07d25872009-06-02 05:28:56 +00003451 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3452 LHS.getCVRQualifiers());
3453 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003454 if (!Result.isNull()) {
3455 if (Result.getObjCGCAttr() == QualType::GCNone)
3456 Result = getObjCGCQualType(Result, GCAttr);
3457 else if (Result.getObjCGCAttr() != GCAttr)
3458 Result = QualType();
3459 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003460 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003461 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003462 }
3463
Eli Friedman4c721d32008-02-12 08:23:06 +00003464 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003465 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3466 LHSClass = Type::ConstantArray;
3467 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3468 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003469
Nate Begeman213541a2008-04-18 23:10:10 +00003470 // Canonicalize ExtVector -> Vector.
3471 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3472 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003473
Chris Lattnerb0489812008-04-07 06:38:24 +00003474 // Consider qualified interfaces and interfaces the same.
Steve Naroff14108da2009-07-10 23:34:53 +00003475 // FIXME: Remove (ObjCObjectPointerType should obsolete this funny business).
Chris Lattnerb0489812008-04-07 06:38:24 +00003476 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3477 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003478
Chris Lattnera36a61f2008-04-07 05:43:21 +00003479 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003480 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003481 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3482 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003483 if (const EnumType* ETy = LHS->getAsEnumType()) {
3484 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3485 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003486 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003487 if (const EnumType* ETy = RHS->getAsEnumType()) {
3488 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3489 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003490 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003491
Eli Friedman3d815e72008-08-22 00:56:42 +00003492 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003493 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003494
Steve Naroff4a746782008-01-09 22:43:08 +00003495 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003496 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003497#define TYPE(Class, Base)
3498#define ABSTRACT_TYPE(Class, Base)
3499#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3500#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3501#include "clang/AST/TypeNodes.def"
3502 assert(false && "Non-canonical and dependent types shouldn't get here");
3503 return QualType();
3504
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003505 case Type::LValueReference:
3506 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003507 case Type::MemberPointer:
3508 assert(false && "C++ should never be in mergeTypes");
3509 return QualType();
3510
3511 case Type::IncompleteArray:
3512 case Type::VariableArray:
3513 case Type::FunctionProto:
3514 case Type::ExtVector:
3515 case Type::ObjCQualifiedInterface:
3516 assert(false && "Types are eliminated above");
3517 return QualType();
3518
Chris Lattner1adb8832008-01-14 05:45:46 +00003519 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003520 {
3521 // Merge two pointer types, while trying to preserve typedef info
3522 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3523 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3524 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3525 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003526 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003527 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003528 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003529 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003530 return getPointerType(ResultType);
3531 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003532 case Type::BlockPointer:
3533 {
3534 // Merge two block pointer types, while trying to preserve typedef info
3535 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3536 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3537 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3538 if (ResultType.isNull()) return QualType();
3539 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3540 return LHS;
3541 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3542 return RHS;
3543 return getBlockPointerType(ResultType);
3544 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003545 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003546 {
3547 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3548 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3549 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3550 return QualType();
3551
3552 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3553 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3554 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3555 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003556 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3557 return LHS;
3558 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3559 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003560 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3561 ArrayType::ArraySizeModifier(), 0);
3562 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3563 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003564 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3565 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003566 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3567 return LHS;
3568 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3569 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003570 if (LVAT) {
3571 // FIXME: This isn't correct! But tricky to implement because
3572 // the array's size has to be the size of LHS, but the type
3573 // has to be different.
3574 return LHS;
3575 }
3576 if (RVAT) {
3577 // FIXME: This isn't correct! But tricky to implement because
3578 // the array's size has to be the size of RHS, but the type
3579 // has to be different.
3580 return RHS;
3581 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003582 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3583 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003584 return getIncompleteArrayType(ResultType,
3585 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003586 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003587 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003588 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003589 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003590 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003591 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003592 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003593 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003594 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003595 case Type::Complex:
3596 // Distinct complex types are incompatible.
3597 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003598 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003599 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003600 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3601 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003602 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003603 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003604 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003605 // FIXME: This should be type compatibility, e.g. whether
3606 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003607 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3608 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3609 if (LHSIface && RHSIface &&
3610 canAssignObjCInterfaces(LHSIface, RHSIface))
3611 return LHS;
3612
Eli Friedman3d815e72008-08-22 00:56:42 +00003613 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003614 }
Steve Naroff14108da2009-07-10 23:34:53 +00003615 case Type::ObjCObjectPointer: {
3616 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3617 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3618 return QualType();
3619
3620 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3621 RHS->getAsObjCObjectPointerType()))
3622 return LHS;
3623
Steve Naroffbc76dd02008-12-10 22:14:21 +00003624 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003625 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003626 case Type::FixedWidthInt:
3627 // Distinct fixed-width integers are not compatible.
3628 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003629 case Type::ExtQual:
3630 // FIXME: ExtQual types can be compatible even if they're not
3631 // identical!
3632 return QualType();
3633 // First attempt at an implementation, but I'm not really sure it's
3634 // right...
3635#if 0
3636 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3637 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3638 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3639 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3640 return QualType();
3641 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3642 LHSBase = QualType(LQual->getBaseType(), 0);
3643 RHSBase = QualType(RQual->getBaseType(), 0);
3644 ResultType = mergeTypes(LHSBase, RHSBase);
3645 if (ResultType.isNull()) return QualType();
3646 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3647 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3648 return LHS;
3649 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3650 return RHS;
3651 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3652 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3653 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3654 return ResultType;
3655#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003656
3657 case Type::TemplateSpecialization:
3658 assert(false && "Dependent types have no size");
3659 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003660 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003661
3662 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003663}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003664
Chris Lattner5426bf62008-04-07 07:01:58 +00003665//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003666// Integer Predicates
3667//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003668
Eli Friedmanad74a752008-06-28 06:23:08 +00003669unsigned ASTContext::getIntWidth(QualType T) {
3670 if (T == BoolTy)
3671 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003672 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3673 return FWIT->getWidth();
3674 }
3675 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003676 return (unsigned)getTypeSize(T);
3677}
3678
3679QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3680 assert(T->isSignedIntegerType() && "Unexpected type");
3681 if (const EnumType* ETy = T->getAsEnumType())
3682 T = ETy->getDecl()->getIntegerType();
3683 const BuiltinType* BTy = T->getAsBuiltinType();
3684 assert (BTy && "Unexpected signed integer type");
3685 switch (BTy->getKind()) {
3686 case BuiltinType::Char_S:
3687 case BuiltinType::SChar:
3688 return UnsignedCharTy;
3689 case BuiltinType::Short:
3690 return UnsignedShortTy;
3691 case BuiltinType::Int:
3692 return UnsignedIntTy;
3693 case BuiltinType::Long:
3694 return UnsignedLongTy;
3695 case BuiltinType::LongLong:
3696 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003697 case BuiltinType::Int128:
3698 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003699 default:
3700 assert(0 && "Unexpected signed integer type");
3701 return QualType();
3702 }
3703}
3704
Douglas Gregor2cf26342009-04-09 22:27:44 +00003705ExternalASTSource::~ExternalASTSource() { }
3706
3707void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003708
3709
3710//===----------------------------------------------------------------------===//
3711// Builtin Type Computation
3712//===----------------------------------------------------------------------===//
3713
3714/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3715/// pointer over the consumed characters. This returns the resultant type.
3716static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3717 ASTContext::GetBuiltinTypeError &Error,
3718 bool AllowTypeModifiers = true) {
3719 // Modifiers.
3720 int HowLong = 0;
3721 bool Signed = false, Unsigned = false;
3722
3723 // Read the modifiers first.
3724 bool Done = false;
3725 while (!Done) {
3726 switch (*Str++) {
3727 default: Done = true; --Str; break;
3728 case 'S':
3729 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3730 assert(!Signed && "Can't use 'S' modifier multiple times!");
3731 Signed = true;
3732 break;
3733 case 'U':
3734 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3735 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3736 Unsigned = true;
3737 break;
3738 case 'L':
3739 assert(HowLong <= 2 && "Can't have LLLL modifier");
3740 ++HowLong;
3741 break;
3742 }
3743 }
3744
3745 QualType Type;
3746
3747 // Read the base type.
3748 switch (*Str++) {
3749 default: assert(0 && "Unknown builtin type letter!");
3750 case 'v':
3751 assert(HowLong == 0 && !Signed && !Unsigned &&
3752 "Bad modifiers used with 'v'!");
3753 Type = Context.VoidTy;
3754 break;
3755 case 'f':
3756 assert(HowLong == 0 && !Signed && !Unsigned &&
3757 "Bad modifiers used with 'f'!");
3758 Type = Context.FloatTy;
3759 break;
3760 case 'd':
3761 assert(HowLong < 2 && !Signed && !Unsigned &&
3762 "Bad modifiers used with 'd'!");
3763 if (HowLong)
3764 Type = Context.LongDoubleTy;
3765 else
3766 Type = Context.DoubleTy;
3767 break;
3768 case 's':
3769 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3770 if (Unsigned)
3771 Type = Context.UnsignedShortTy;
3772 else
3773 Type = Context.ShortTy;
3774 break;
3775 case 'i':
3776 if (HowLong == 3)
3777 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3778 else if (HowLong == 2)
3779 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3780 else if (HowLong == 1)
3781 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3782 else
3783 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3784 break;
3785 case 'c':
3786 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3787 if (Signed)
3788 Type = Context.SignedCharTy;
3789 else if (Unsigned)
3790 Type = Context.UnsignedCharTy;
3791 else
3792 Type = Context.CharTy;
3793 break;
3794 case 'b': // boolean
3795 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3796 Type = Context.BoolTy;
3797 break;
3798 case 'z': // size_t.
3799 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3800 Type = Context.getSizeType();
3801 break;
3802 case 'F':
3803 Type = Context.getCFConstantStringType();
3804 break;
3805 case 'a':
3806 Type = Context.getBuiltinVaListType();
3807 assert(!Type.isNull() && "builtin va list type not initialized!");
3808 break;
3809 case 'A':
3810 // This is a "reference" to a va_list; however, what exactly
3811 // this means depends on how va_list is defined. There are two
3812 // different kinds of va_list: ones passed by value, and ones
3813 // passed by reference. An example of a by-value va_list is
3814 // x86, where va_list is a char*. An example of by-ref va_list
3815 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3816 // we want this argument to be a char*&; for x86-64, we want
3817 // it to be a __va_list_tag*.
3818 Type = Context.getBuiltinVaListType();
3819 assert(!Type.isNull() && "builtin va list type not initialized!");
3820 if (Type->isArrayType()) {
3821 Type = Context.getArrayDecayedType(Type);
3822 } else {
3823 Type = Context.getLValueReferenceType(Type);
3824 }
3825 break;
3826 case 'V': {
3827 char *End;
3828
3829 unsigned NumElements = strtoul(Str, &End, 10);
3830 assert(End != Str && "Missing vector size");
3831
3832 Str = End;
3833
3834 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3835 Type = Context.getVectorType(ElementType, NumElements);
3836 break;
3837 }
3838 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003839 Type = Context.getFILEType();
3840 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003841 Error = ASTContext::GE_Missing_FILE;
3842 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003843 } else {
3844 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003845 }
3846 }
3847 }
3848
3849 if (!AllowTypeModifiers)
3850 return Type;
3851
3852 Done = false;
3853 while (!Done) {
3854 switch (*Str++) {
3855 default: Done = true; --Str; break;
3856 case '*':
3857 Type = Context.getPointerType(Type);
3858 break;
3859 case '&':
3860 Type = Context.getLValueReferenceType(Type);
3861 break;
3862 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3863 case 'C':
3864 Type = Type.getQualifiedType(QualType::Const);
3865 break;
3866 }
3867 }
3868
3869 return Type;
3870}
3871
3872/// GetBuiltinType - Return the type for the specified builtin.
3873QualType ASTContext::GetBuiltinType(unsigned id,
3874 GetBuiltinTypeError &Error) {
3875 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3876
3877 llvm::SmallVector<QualType, 8> ArgTypes;
3878
3879 Error = GE_None;
3880 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3881 if (Error != GE_None)
3882 return QualType();
3883 while (TypeStr[0] && TypeStr[0] != '.') {
3884 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3885 if (Error != GE_None)
3886 return QualType();
3887
3888 // Do array -> pointer decay. The builtin should use the decayed type.
3889 if (Ty->isArrayType())
3890 Ty = getArrayDecayedType(Ty);
3891
3892 ArgTypes.push_back(Ty);
3893 }
3894
3895 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3896 "'.' should only occur at end of builtin type list!");
3897
3898 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3899 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3900 return getFunctionNoProtoType(ResType);
3901 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3902 TypeStr[0] == '.', 0);
3903}