blob: 046b27c9f3207197dd75de117c047ffb1718a174 [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();
Ted Kremenek35366a62009-07-17 17:50:17 +0000450 if (const ReferenceType* RT = T->getAsReferenceType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000451 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());
Ted Kremenek35366a62009-07-17 17:50:17 +0000782 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000783 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()) {
Ted Kremenek35366a62009-07-17 17:50:17 +00001095 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 Gregor25a3ef72009-05-07 06:41:52 +00002085TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2086 // If this template name refers to a template, the canonical
2087 // template name merely stores the template itself.
2088 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002089 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002090
2091 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2092 assert(DTN && "Non-dependent template names must refer to template decls.");
2093 return DTN->CanonicalTemplateName;
2094}
2095
Douglas Gregord57959a2009-03-27 23:10:48 +00002096NestedNameSpecifier *
2097ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2098 if (!NNS)
2099 return 0;
2100
2101 switch (NNS->getKind()) {
2102 case NestedNameSpecifier::Identifier:
2103 // Canonicalize the prefix but keep the identifier the same.
2104 return NestedNameSpecifier::Create(*this,
2105 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2106 NNS->getAsIdentifier());
2107
2108 case NestedNameSpecifier::Namespace:
2109 // A namespace is canonical; build a nested-name-specifier with
2110 // this namespace and no prefix.
2111 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2112
2113 case NestedNameSpecifier::TypeSpec:
2114 case NestedNameSpecifier::TypeSpecWithTemplate: {
2115 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2116 NestedNameSpecifier *Prefix = 0;
2117
2118 // FIXME: This isn't the right check!
2119 if (T->isDependentType())
2120 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2121
2122 return NestedNameSpecifier::Create(*this, Prefix,
2123 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2124 T.getTypePtr());
2125 }
2126
2127 case NestedNameSpecifier::Global:
2128 // The global specifier is canonical and unique.
2129 return NNS;
2130 }
2131
2132 // Required to silence a GCC warning
2133 return 0;
2134}
2135
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002136
2137const ArrayType *ASTContext::getAsArrayType(QualType T) {
2138 // Handle the non-qualified case efficiently.
2139 if (T.getCVRQualifiers() == 0) {
2140 // Handle the common positive case fast.
2141 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2142 return AT;
2143 }
2144
2145 // Handle the common negative case fast, ignoring CVR qualifiers.
2146 QualType CType = T->getCanonicalTypeInternal();
2147
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002148 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002149 // test.
2150 if (!isa<ArrayType>(CType) &&
2151 !isa<ArrayType>(CType.getUnqualifiedType()))
2152 return 0;
2153
2154 // Apply any CVR qualifiers from the array type to the element type. This
2155 // implements C99 6.7.3p8: "If the specification of an array type includes
2156 // any type qualifiers, the element type is so qualified, not the array type."
2157
2158 // If we get here, we either have type qualifiers on the type, or we have
2159 // sugar such as a typedef in the way. If we have type qualifiers on the type
2160 // we must propagate them down into the elemeng type.
2161 unsigned CVRQuals = T.getCVRQualifiers();
2162 unsigned AddrSpace = 0;
2163 Type *Ty = T.getTypePtr();
2164
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002165 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002166 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002167 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2168 AddrSpace = EXTQT->getAddressSpace();
2169 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002170 } else {
2171 T = Ty->getDesugaredType();
2172 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2173 break;
2174 CVRQuals |= T.getCVRQualifiers();
2175 Ty = T.getTypePtr();
2176 }
2177 }
2178
2179 // If we have a simple case, just return now.
2180 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2181 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2182 return ATy;
2183
2184 // Otherwise, we have an array and we have qualifiers on it. Push the
2185 // qualifiers into the array element type and return a new array type.
2186 // Get the canonical version of the element with the extra qualifiers on it.
2187 // This can recursively sink qualifiers through multiple levels of arrays.
2188 QualType NewEltTy = ATy->getElementType();
2189 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002190 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002191 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2192
2193 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2194 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2195 CAT->getSizeModifier(),
2196 CAT->getIndexTypeQualifier()));
2197 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2198 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2199 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002200 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002201
Douglas Gregor898574e2008-12-05 23:32:09 +00002202 if (const DependentSizedArrayType *DSAT
2203 = dyn_cast<DependentSizedArrayType>(ATy))
2204 return cast<ArrayType>(
2205 getDependentSizedArrayType(NewEltTy,
2206 DSAT->getSizeExpr(),
2207 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002208 DSAT->getIndexTypeQualifier(),
2209 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002210
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002211 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002212 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2213 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002214 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002215 VAT->getIndexTypeQualifier(),
2216 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002217}
2218
2219
Chris Lattnere6327742008-04-02 05:18:44 +00002220/// getArrayDecayedType - Return the properly qualified result of decaying the
2221/// specified array type to a pointer. This operation is non-trivial when
2222/// handling typedefs etc. The canonical type of "T" must be an array type,
2223/// this returns a pointer to a properly qualified element of the array.
2224///
2225/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2226QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002227 // Get the element type with 'getAsArrayType' so that we don't lose any
2228 // typedefs in the element type of the array. This also handles propagation
2229 // of type qualifiers from the array type into the element type if present
2230 // (C99 6.7.3p8).
2231 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2232 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002233
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002234 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002235
2236 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002237 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002238}
2239
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002240QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002241 QualType ElemTy = VAT->getElementType();
2242
2243 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2244 return getBaseElementType(VAT);
2245
2246 return ElemTy;
2247}
2248
Reid Spencer5f016e22007-07-11 17:01:13 +00002249/// getFloatingRank - Return a relative rank for floating point types.
2250/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002251static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002252 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002254
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002255 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002256 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002257 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 case BuiltinType::Float: return FloatRank;
2259 case BuiltinType::Double: return DoubleRank;
2260 case BuiltinType::LongDouble: return LongDoubleRank;
2261 }
2262}
2263
Steve Naroff716c7302007-08-27 01:41:48 +00002264/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2265/// point or a complex type (based on typeDomain/typeSize).
2266/// 'typeDomain' is a real floating point or complex type.
2267/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002268QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2269 QualType Domain) const {
2270 FloatingRank EltRank = getFloatingRank(Size);
2271 if (Domain->isComplexType()) {
2272 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002273 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002274 case FloatRank: return FloatComplexTy;
2275 case DoubleRank: return DoubleComplexTy;
2276 case LongDoubleRank: return LongDoubleComplexTy;
2277 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 }
Chris Lattner1361b112008-04-06 23:58:54 +00002279
2280 assert(Domain->isRealFloatingType() && "Unknown domain!");
2281 switch (EltRank) {
2282 default: assert(0 && "getFloatingRank(): illegal value for rank");
2283 case FloatRank: return FloatTy;
2284 case DoubleRank: return DoubleTy;
2285 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002286 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002287}
2288
Chris Lattner7cfeb082008-04-06 23:55:33 +00002289/// getFloatingTypeOrder - Compare the rank of the two specified floating
2290/// point types, ignoring the domain of the type (i.e. 'double' ==
2291/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2292/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002293int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2294 FloatingRank LHSR = getFloatingRank(LHS);
2295 FloatingRank RHSR = getFloatingRank(RHS);
2296
2297 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002298 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002299 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002300 return 1;
2301 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002302}
2303
Chris Lattnerf52ab252008-04-06 22:59:24 +00002304/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2305/// routine will assert if passed a built-in type that isn't an integer or enum,
2306/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002307unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002308 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002309 if (EnumType* ET = dyn_cast<EnumType>(T))
2310 T = ET->getDecl()->getIntegerType().getTypePtr();
2311
Eli Friedmana3426752009-07-05 23:44:27 +00002312 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2313 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2314
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002315 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2316 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2317
2318 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2319 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2320
Eli Friedmanf98aba32009-02-13 02:31:07 +00002321 // There are two things which impact the integer rank: the width, and
2322 // the ordering of builtins. The builtin ordering is encoded in the
2323 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002324 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002325 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002326
Chris Lattnerf52ab252008-04-06 22:59:24 +00002327 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002328 default: assert(0 && "getIntegerRank(): not a built-in integer");
2329 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002330 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002331 case BuiltinType::Char_S:
2332 case BuiltinType::Char_U:
2333 case BuiltinType::SChar:
2334 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002335 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002336 case BuiltinType::Short:
2337 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002338 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002339 case BuiltinType::Int:
2340 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002341 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002342 case BuiltinType::Long:
2343 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002344 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002345 case BuiltinType::LongLong:
2346 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002347 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002348 case BuiltinType::Int128:
2349 case BuiltinType::UInt128:
2350 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002351 }
2352}
2353
Chris Lattner7cfeb082008-04-06 23:55:33 +00002354/// getIntegerTypeOrder - Returns the highest ranked integer type:
2355/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2356/// LHS < RHS, return -1.
2357int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002358 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2359 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002360 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002361
Chris Lattnerf52ab252008-04-06 22:59:24 +00002362 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2363 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002364
Chris Lattner7cfeb082008-04-06 23:55:33 +00002365 unsigned LHSRank = getIntegerRank(LHSC);
2366 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002367
Chris Lattner7cfeb082008-04-06 23:55:33 +00002368 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2369 if (LHSRank == RHSRank) return 0;
2370 return LHSRank > RHSRank ? 1 : -1;
2371 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002372
Chris Lattner7cfeb082008-04-06 23:55:33 +00002373 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2374 if (LHSUnsigned) {
2375 // If the unsigned [LHS] type is larger, return it.
2376 if (LHSRank >= RHSRank)
2377 return 1;
2378
2379 // If the signed type can represent all values of the unsigned type, it
2380 // wins. Because we are dealing with 2's complement and types that are
2381 // powers of two larger than each other, this is always safe.
2382 return -1;
2383 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002384
Chris Lattner7cfeb082008-04-06 23:55:33 +00002385 // If the unsigned [RHS] type is larger, return it.
2386 if (RHSRank >= LHSRank)
2387 return -1;
2388
2389 // If the signed type can represent all values of the unsigned type, it
2390 // wins. Because we are dealing with 2's complement and types that are
2391 // powers of two larger than each other, this is always safe.
2392 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002393}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002394
2395// getCFConstantStringType - Return the type used for constant CFStrings.
2396QualType ASTContext::getCFConstantStringType() {
2397 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002398 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002399 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002400 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002401 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002402
2403 // const int *isa;
2404 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002405 // int flags;
2406 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002407 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002408 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002409 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002410 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002411
Anders Carlsson71993dd2007-08-17 05:31:46 +00002412 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002413 for (unsigned i = 0; i < 4; ++i) {
2414 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2415 SourceLocation(), 0,
2416 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002417 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002418 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002419 }
2420
2421 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002422 }
2423
2424 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002425}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002426
Douglas Gregor319ac892009-04-23 22:29:11 +00002427void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002428 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002429 assert(Rec && "Invalid CFConstantStringType");
2430 CFConstantStringTypeDecl = Rec->getDecl();
2431}
2432
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002433QualType ASTContext::getObjCFastEnumerationStateType()
2434{
2435 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002436 ObjCFastEnumerationStateTypeDecl =
2437 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2438 &Idents.get("__objcFastEnumerationState"));
2439
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002440 QualType FieldTypes[] = {
2441 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002442 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002443 getPointerType(UnsignedLongTy),
2444 getConstantArrayType(UnsignedLongTy,
2445 llvm::APInt(32, 5), ArrayType::Normal, 0)
2446 };
2447
Douglas Gregor44b43212008-12-11 16:49:14 +00002448 for (size_t i = 0; i < 4; ++i) {
2449 FieldDecl *Field = FieldDecl::Create(*this,
2450 ObjCFastEnumerationStateTypeDecl,
2451 SourceLocation(), 0,
2452 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002453 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002454 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002455 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002456
Douglas Gregor44b43212008-12-11 16:49:14 +00002457 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002458 }
2459
2460 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2461}
2462
Douglas Gregor319ac892009-04-23 22:29:11 +00002463void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002464 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002465 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2466 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2467}
2468
Anders Carlssone8c49532007-10-29 06:33:42 +00002469// This returns true if a type has been typedefed to BOOL:
2470// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002471static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002472 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002473 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2474 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002475
2476 return false;
2477}
2478
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002479/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002480/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002481int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002482 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002483
2484 // Make all integer and enum types at least as large as an int
2485 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002486 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002487 // Treat arrays as pointers, since that's how they're passed in.
2488 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002489 sz = getTypeSize(VoidPtrTy);
2490 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002491}
2492
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002494/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002495void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002496 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002497 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002498 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002499 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002500 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002501 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002502 // Compute size of all parameters.
2503 // Start with computing size of a pointer in number of bytes.
2504 // FIXME: There might(should) be a better way of doing this computation!
2505 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002506 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002507 // The first two arguments (self and _cmd) are pointers; account for
2508 // their size.
2509 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002510 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2511 E = Decl->param_end(); PI != E; ++PI) {
2512 QualType PType = (*PI)->getType();
2513 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002514 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002515 ParmOffset += sz;
2516 }
2517 S += llvm::utostr(ParmOffset);
2518 S += "@0:";
2519 S += llvm::utostr(PtrSize);
2520
2521 // Argument types.
2522 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002523 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2524 E = Decl->param_end(); PI != E; ++PI) {
2525 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002526 QualType PType = PVDecl->getOriginalType();
2527 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002528 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2529 // Use array's original type only if it has known number of
2530 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002531 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002532 PType = PVDecl->getType();
2533 } else if (PType->isFunctionType())
2534 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002535 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002536 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002537 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002538 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002539 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002540 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002541 }
2542}
2543
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002544/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002545/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002546/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2547/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002548/// Property attributes are stored as a comma-delimited C string. The simple
2549/// attributes readonly and bycopy are encoded as single characters. The
2550/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2551/// encoded as single characters, followed by an identifier. Property types
2552/// are also encoded as a parametrized attribute. The characters used to encode
2553/// these attributes are defined by the following enumeration:
2554/// @code
2555/// enum PropertyAttributes {
2556/// kPropertyReadOnly = 'R', // property is read-only.
2557/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2558/// kPropertyByref = '&', // property is a reference to the value last assigned
2559/// kPropertyDynamic = 'D', // property is dynamic
2560/// kPropertyGetter = 'G', // followed by getter selector name
2561/// kPropertySetter = 'S', // followed by setter selector name
2562/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2563/// kPropertyType = 't' // followed by old-style type encoding.
2564/// kPropertyWeak = 'W' // 'weak' property
2565/// kPropertyStrong = 'P' // property GC'able
2566/// kPropertyNonAtomic = 'N' // property non-atomic
2567/// };
2568/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002569void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2570 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002571 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002572 // Collect information from the property implementation decl(s).
2573 bool Dynamic = false;
2574 ObjCPropertyImplDecl *SynthesizePID = 0;
2575
2576 // FIXME: Duplicated code due to poor abstraction.
2577 if (Container) {
2578 if (const ObjCCategoryImplDecl *CID =
2579 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2580 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002581 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002582 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002583 ObjCPropertyImplDecl *PID = *i;
2584 if (PID->getPropertyDecl() == PD) {
2585 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2586 Dynamic = true;
2587 } else {
2588 SynthesizePID = PID;
2589 }
2590 }
2591 }
2592 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002593 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002594 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002595 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002596 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002597 ObjCPropertyImplDecl *PID = *i;
2598 if (PID->getPropertyDecl() == PD) {
2599 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2600 Dynamic = true;
2601 } else {
2602 SynthesizePID = PID;
2603 }
2604 }
2605 }
2606 }
2607 }
2608
2609 // FIXME: This is not very efficient.
2610 S = "T";
2611
2612 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002613 // GCC has some special rules regarding encoding of properties which
2614 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002615 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002616 true /* outermost type */,
2617 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002618
2619 if (PD->isReadOnly()) {
2620 S += ",R";
2621 } else {
2622 switch (PD->getSetterKind()) {
2623 case ObjCPropertyDecl::Assign: break;
2624 case ObjCPropertyDecl::Copy: S += ",C"; break;
2625 case ObjCPropertyDecl::Retain: S += ",&"; break;
2626 }
2627 }
2628
2629 // It really isn't clear at all what this means, since properties
2630 // are "dynamic by default".
2631 if (Dynamic)
2632 S += ",D";
2633
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002634 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2635 S += ",N";
2636
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002637 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2638 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002639 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002640 }
2641
2642 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2643 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002644 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002645 }
2646
2647 if (SynthesizePID) {
2648 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2649 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002650 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002651 }
2652
2653 // FIXME: OBJCGC: weak & strong
2654}
2655
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002656/// getLegacyIntegralTypeEncoding -
2657/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002658/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002659/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2660///
2661void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2662 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2663 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002664 if (BT->getKind() == BuiltinType::ULong &&
2665 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002666 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002667 else
2668 if (BT->getKind() == BuiltinType::Long &&
2669 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002670 PointeeTy = IntTy;
2671 }
2672 }
2673}
2674
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002675void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002676 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002677 // We follow the behavior of gcc, expanding structures which are
2678 // directly pointed to, and expanding embedded structures. Note that
2679 // these rules are sufficient to prevent recursive encoding of the
2680 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002681 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2682 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002683}
2684
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002685static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002686 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002687 const Expr *E = FD->getBitWidth();
2688 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2689 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002690 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002691 S += 'b';
2692 S += llvm::utostr(N);
2693}
2694
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002695void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2696 bool ExpandPointedToStructures,
2697 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002698 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002699 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002700 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002701 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002702 if (FD && FD->isBitField())
2703 return EncodeBitField(this, S, FD);
2704 char encoding;
2705 switch (BT->getKind()) {
2706 default: assert(0 && "Unhandled builtin type kind");
2707 case BuiltinType::Void: encoding = 'v'; break;
2708 case BuiltinType::Bool: encoding = 'B'; break;
2709 case BuiltinType::Char_U:
2710 case BuiltinType::UChar: encoding = 'C'; break;
2711 case BuiltinType::UShort: encoding = 'S'; break;
2712 case BuiltinType::UInt: encoding = 'I'; break;
2713 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002714 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002715 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002716 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002717 case BuiltinType::UInt128: encoding = 'T'; break;
2718 case BuiltinType::ULongLong: encoding = 'Q'; break;
2719 case BuiltinType::Char_S:
2720 case BuiltinType::SChar: encoding = 'c'; break;
2721 case BuiltinType::Short: encoding = 's'; break;
2722 case BuiltinType::Int: encoding = 'i'; break;
2723 case BuiltinType::Long:
2724 encoding =
2725 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2726 break;
2727 case BuiltinType::LongLong: encoding = 'q'; break;
2728 case BuiltinType::Int128: encoding = 't'; break;
2729 case BuiltinType::Float: encoding = 'f'; break;
2730 case BuiltinType::Double: encoding = 'd'; break;
2731 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002732 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002733
2734 S += encoding;
2735 return;
2736 }
2737
2738 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002739 S += 'j';
2740 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2741 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002742 return;
2743 }
2744
Ted Kremenek35366a62009-07-17 17:50:17 +00002745 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002746 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002747 bool isReadOnly = false;
2748 // For historical/compatibility reasons, the read-only qualifier of the
2749 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2750 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2751 // Also, do not emit the 'r' for anything but the outermost type!
2752 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2753 if (OutermostType && T.isConstQualified()) {
2754 isReadOnly = true;
2755 S += 'r';
2756 }
2757 }
2758 else if (OutermostType) {
2759 QualType P = PointeeTy;
Ted Kremenek35366a62009-07-17 17:50:17 +00002760 while (P->getAsPointerType())
2761 P = P->getAsPointerType()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002762 if (P.isConstQualified()) {
2763 isReadOnly = true;
2764 S += 'r';
2765 }
2766 }
2767 if (isReadOnly) {
2768 // Another legacy compatibility encoding. Some ObjC qualifier and type
2769 // combinations need to be rearranged.
2770 // Rewrite "in const" from "nr" to "rn"
2771 const char * s = S.c_str();
2772 int len = S.length();
2773 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2774 std::string replace = "rn";
2775 S.replace(S.end()-2, S.end(), replace);
2776 }
2777 }
Steve Naroff14108da2009-07-10 23:34:53 +00002778 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002779 S += ':';
2780 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002781 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002782
2783 if (PointeeTy->isCharType()) {
2784 // char pointer types should be encoded as '*' unless it is a
2785 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002786 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002787 S += '*';
2788 return;
2789 }
2790 }
2791
2792 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002793 getLegacyIntegralTypeEncoding(PointeeTy);
2794
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002795 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002796 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002797 return;
2798 }
2799
2800 if (const ArrayType *AT =
2801 // Ignore type qualifiers etc.
2802 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002803 if (isa<IncompleteArrayType>(AT)) {
2804 // Incomplete arrays are encoded as a pointer to the array element.
2805 S += '^';
2806
2807 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2808 false, ExpandStructures, FD);
2809 } else {
2810 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002811
Anders Carlsson559a8332009-02-22 01:38:57 +00002812 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2813 S += llvm::utostr(CAT->getSize().getZExtValue());
2814 else {
2815 //Variable length arrays are encoded as a regular array with 0 elements.
2816 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2817 S += '0';
2818 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002819
Anders Carlsson559a8332009-02-22 01:38:57 +00002820 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2821 false, ExpandStructures, FD);
2822 S += ']';
2823 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002824 return;
2825 }
2826
2827 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002828 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002829 return;
2830 }
2831
Ted Kremenek35366a62009-07-17 17:50:17 +00002832 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002833 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002834 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002835 // Anonymous structures print as '?'
2836 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2837 S += II->getName();
2838 } else {
2839 S += '?';
2840 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002841 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002842 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002843 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2844 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002845 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002846 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002847 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002848 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002849 S += '"';
2850 }
2851
2852 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002853 if (Field->isBitField()) {
2854 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2855 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002856 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002857 QualType qt = Field->getType();
2858 getLegacyIntegralTypeEncoding(qt);
2859 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002860 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002861 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002862 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002863 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002864 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002865 return;
2866 }
2867
2868 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002869 if (FD && FD->isBitField())
2870 EncodeBitField(this, S, FD);
2871 else
2872 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002873 return;
2874 }
2875
2876 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002877 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002878 return;
2879 }
2880
2881 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002882 // @encode(class_name)
2883 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2884 S += '{';
2885 const IdentifierInfo *II = OI->getIdentifier();
2886 S += II->getName();
2887 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002888 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002889 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002890 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002891 if (RecFields[i]->isBitField())
2892 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2893 RecFields[i]);
2894 else
2895 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2896 FD);
2897 }
2898 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002899 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002900 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002901
2902 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002903 if (OPT->isObjCIdType()) {
2904 S += '@';
2905 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002906 }
2907
2908 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002909 S += '#';
2910 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002911 }
2912
2913 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002914 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2915 ExpandPointedToStructures,
2916 ExpandStructures, FD);
2917 if (FD || EncodingProperty) {
2918 // Note that we do extended encoding of protocol qualifer list
2919 // Only when doing ivar or property encoding.
2920 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2921 S += '"';
2922 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2923 E = QIDT->qual_end(); I != E; ++I) {
2924 S += '<';
2925 S += (*I)->getNameAsString();
2926 S += '>';
2927 }
2928 S += '"';
2929 }
2930 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002931 }
2932
2933 QualType PointeeTy = OPT->getPointeeType();
2934 if (!EncodingProperty &&
2935 isa<TypedefType>(PointeeTy.getTypePtr())) {
2936 // Another historical/compatibility reason.
2937 // We encode the underlying type which comes out as
2938 // {...};
2939 S += '^';
2940 getObjCEncodingForTypeImpl(PointeeTy, S,
2941 false, ExpandPointedToStructures,
2942 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00002943 return;
2944 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002945
2946 S += '@';
2947 if (FD || EncodingProperty) {
2948 const ObjCInterfaceType *OIT = OPT->getInterfaceType();
2949 ObjCInterfaceDecl *OI = OIT->getDecl();
2950 S += '"';
2951 S += OI->getNameAsCString();
2952 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2953 E = OIT->qual_end(); I != E; ++I) {
2954 S += '<';
2955 S += (*I)->getNameAsString();
2956 S += '>';
2957 }
2958 S += '"';
2959 }
2960 return;
2961 }
2962
2963 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002964}
2965
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002966void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002967 std::string& S) const {
2968 if (QT & Decl::OBJC_TQ_In)
2969 S += 'n';
2970 if (QT & Decl::OBJC_TQ_Inout)
2971 S += 'N';
2972 if (QT & Decl::OBJC_TQ_Out)
2973 S += 'o';
2974 if (QT & Decl::OBJC_TQ_Bycopy)
2975 S += 'O';
2976 if (QT & Decl::OBJC_TQ_Byref)
2977 S += 'R';
2978 if (QT & Decl::OBJC_TQ_Oneway)
2979 S += 'V';
2980}
2981
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002982void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002983 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2984
2985 BuiltinVaListType = T;
2986}
2987
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002988void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002989 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00002990}
2991
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002992void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00002993 ObjCSelType = T;
2994
2995 const TypedefType *TT = T->getAsTypedefType();
2996 if (!TT)
2997 return;
2998 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002999
3000 // typedef struct objc_selector *SEL;
Ted Kremenek35366a62009-07-17 17:50:17 +00003001 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003002 if (!ptr)
3003 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003004 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003005 if (!rec)
3006 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003007 SelStructType = rec;
3008}
3009
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003010void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003011 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003012}
3013
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003014void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003015 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003016}
3017
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003018void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3019 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003020 "'NSConstantString' type already set!");
3021
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003022 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003023}
3024
Douglas Gregor7532dc62009-03-30 22:58:21 +00003025/// \brief Retrieve the template name that represents a qualified
3026/// template name such as \c std::vector.
3027TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3028 bool TemplateKeyword,
3029 TemplateDecl *Template) {
3030 llvm::FoldingSetNodeID ID;
3031 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3032
3033 void *InsertPos = 0;
3034 QualifiedTemplateName *QTN =
3035 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3036 if (!QTN) {
3037 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3038 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3039 }
3040
3041 return TemplateName(QTN);
3042}
3043
3044/// \brief Retrieve the template name that represents a dependent
3045/// template name such as \c MetaFun::template apply.
3046TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3047 const IdentifierInfo *Name) {
3048 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3049
3050 llvm::FoldingSetNodeID ID;
3051 DependentTemplateName::Profile(ID, NNS, Name);
3052
3053 void *InsertPos = 0;
3054 DependentTemplateName *QTN =
3055 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3056
3057 if (QTN)
3058 return TemplateName(QTN);
3059
3060 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3061 if (CanonNNS == NNS) {
3062 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3063 } else {
3064 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3065 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3066 }
3067
3068 DependentTemplateNames.InsertNode(QTN, InsertPos);
3069 return TemplateName(QTN);
3070}
3071
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003072/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003073/// TargetInfo, produce the corresponding type. The unsigned @p Type
3074/// is actually a value of type @c TargetInfo::IntType.
3075QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003076 switch (Type) {
3077 case TargetInfo::NoInt: return QualType();
3078 case TargetInfo::SignedShort: return ShortTy;
3079 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3080 case TargetInfo::SignedInt: return IntTy;
3081 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3082 case TargetInfo::SignedLong: return LongTy;
3083 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3084 case TargetInfo::SignedLongLong: return LongLongTy;
3085 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3086 }
3087
3088 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003089 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003090}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003091
3092//===----------------------------------------------------------------------===//
3093// Type Predicates.
3094//===----------------------------------------------------------------------===//
3095
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003096/// isObjCNSObjectType - Return true if this is an NSObject object using
3097/// NSObject attribute on a c-style pointer type.
3098/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003099/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003100///
3101bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3102 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3103 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003104 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003105 return true;
3106 }
3107 return false;
3108}
3109
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003110/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3111/// garbage collection attribute.
3112///
3113QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003114 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003115 if (getLangOptions().ObjC1 &&
3116 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003117 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003118 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003119 // (or pointers to them) be treated as though they were declared
3120 // as __strong.
3121 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003122 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003123 GCAttrs = QualType::Strong;
3124 else if (Ty->isPointerType())
Ted Kremenek35366a62009-07-17 17:50:17 +00003125 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003126 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003127 // Non-pointers have none gc'able attribute regardless of the attribute
3128 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003129 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003130 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003131 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003132 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003133}
3134
Chris Lattner6ac46a42008-04-07 06:51:04 +00003135//===----------------------------------------------------------------------===//
3136// Type Compatibility Testing
3137//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003138
Chris Lattner6ac46a42008-04-07 06:51:04 +00003139/// areCompatVectorTypes - Return true if the two specified vector types are
3140/// compatible.
3141static bool areCompatVectorTypes(const VectorType *LHS,
3142 const VectorType *RHS) {
3143 assert(LHS->isCanonical() && RHS->isCanonical());
3144 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003145 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003146}
3147
Eli Friedman3d815e72008-08-22 00:56:42 +00003148/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003149/// compatible for assignment from RHS to LHS. This handles validation of any
3150/// protocol qualifiers on the LHS or RHS.
3151///
Steve Naroff14108da2009-07-10 23:34:53 +00003152/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3153bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3154 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003155 // If either type represents the built-in 'id' or 'Class' types, return true.
3156 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003157 return true;
3158
3159 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3160 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroffde2e22d2009-07-15 18:40:39 +00003161 if (!LHS || !RHS) {
3162 // We have qualified builtin types.
3163 // Both the right and left sides have qualifiers.
3164 for (ObjCObjectPointerType::qual_iterator I = LHSOPT->qual_begin(),
3165 E = LHSOPT->qual_end(); I != E; ++I) {
3166 bool RHSImplementsProtocol = false;
3167
3168 // when comparing an id<P> on lhs with a static type on rhs,
3169 // see if static class implements all of id's protocols, directly or
3170 // through its super class and categories.
3171 for (ObjCObjectPointerType::qual_iterator J = RHSOPT->qual_begin(),
3172 E = RHSOPT->qual_end(); J != E; ++J) {
Steve Naroff8f167562009-07-16 16:21:02 +00003173 if ((*J)->lookupProtocolNamed((*I)->getIdentifier())) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003174 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003175 break;
3176 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003177 }
3178 if (!RHSImplementsProtocol)
3179 return false;
3180 }
3181 // The RHS implements all protocols listed on the LHS.
3182 return true;
3183 }
Steve Naroff14108da2009-07-10 23:34:53 +00003184 return canAssignObjCInterfaces(LHS, RHS);
3185}
3186
Eli Friedman3d815e72008-08-22 00:56:42 +00003187bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3188 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003189 // Verify that the base decls are compatible: the RHS must be a subclass of
3190 // the LHS.
3191 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3192 return false;
3193
3194 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3195 // protocol qualified at all, then we are good.
3196 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3197 return true;
3198
3199 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3200 // isn't a superset.
3201 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3202 return true; // FIXME: should return false!
3203
3204 // Finally, we must have two protocol-qualified interfaces.
3205 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3206 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003207
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003208 // All LHS protocols must have a presence on the RHS.
3209 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003210
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003211 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3212 LHSPE = LHSP->qual_end();
3213 LHSPI != LHSPE; LHSPI++) {
3214 bool RHSImplementsProtocol = false;
3215
3216 // If the RHS doesn't implement the protocol on the left, the types
3217 // are incompatible.
3218 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3219 RHSPE = RHSP->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003220 RHSPI != RHSPE; RHSPI++) {
3221 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003222 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003223 break;
3224 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003225 }
3226 // FIXME: For better diagnostics, consider passing back the protocol name.
3227 if (!RHSImplementsProtocol)
3228 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003229 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003230 // The RHS implements all protocols listed on the LHS.
3231 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003232}
3233
Steve Naroff389bf462009-02-12 17:52:19 +00003234bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3235 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003236 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3237 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003238
Steve Naroff14108da2009-07-10 23:34:53 +00003239 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003240 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003241
3242 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3243 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003244}
3245
Steve Naroffec0550f2007-10-15 20:41:53 +00003246/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3247/// both shall have the identically qualified version of a compatible type.
3248/// C99 6.2.7p1: Two types have compatible types if their types are the
3249/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003250bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3251 return !mergeTypes(LHS, RHS).isNull();
3252}
3253
3254QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3255 const FunctionType *lbase = lhs->getAsFunctionType();
3256 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003257 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3258 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003259 bool allLTypes = true;
3260 bool allRTypes = true;
3261
3262 // Check return type
3263 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3264 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003265 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3266 allLTypes = false;
3267 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3268 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003269
3270 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003271 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3272 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003273 unsigned lproto_nargs = lproto->getNumArgs();
3274 unsigned rproto_nargs = rproto->getNumArgs();
3275
3276 // Compatible functions must have the same number of arguments
3277 if (lproto_nargs != rproto_nargs)
3278 return QualType();
3279
3280 // Variadic and non-variadic functions aren't compatible
3281 if (lproto->isVariadic() != rproto->isVariadic())
3282 return QualType();
3283
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003284 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3285 return QualType();
3286
Eli Friedman3d815e72008-08-22 00:56:42 +00003287 // Check argument compatibility
3288 llvm::SmallVector<QualType, 10> types;
3289 for (unsigned i = 0; i < lproto_nargs; i++) {
3290 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3291 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3292 QualType argtype = mergeTypes(largtype, rargtype);
3293 if (argtype.isNull()) return QualType();
3294 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003295 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3296 allLTypes = false;
3297 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3298 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003299 }
3300 if (allLTypes) return lhs;
3301 if (allRTypes) return rhs;
3302 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003303 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003304 }
3305
3306 if (lproto) allRTypes = false;
3307 if (rproto) allLTypes = false;
3308
Douglas Gregor72564e72009-02-26 23:50:07 +00003309 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003310 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003311 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003312 if (proto->isVariadic()) return QualType();
3313 // Check that the types are compatible with the types that
3314 // would result from default argument promotions (C99 6.7.5.3p15).
3315 // The only types actually affected are promotable integer
3316 // types and floats, which would be passed as a different
3317 // type depending on whether the prototype is visible.
3318 unsigned proto_nargs = proto->getNumArgs();
3319 for (unsigned i = 0; i < proto_nargs; ++i) {
3320 QualType argTy = proto->getArgType(i);
3321 if (argTy->isPromotableIntegerType() ||
3322 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3323 return QualType();
3324 }
3325
3326 if (allLTypes) return lhs;
3327 if (allRTypes) return rhs;
3328 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003329 proto->getNumArgs(), lproto->isVariadic(),
3330 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003331 }
3332
3333 if (allLTypes) return lhs;
3334 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003335 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003336}
3337
3338QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003339 // C++ [expr]: If an expression initially has the type "reference to T", the
3340 // type is adjusted to "T" prior to any further analysis, the expression
3341 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003342 // expression is an lvalue unless the reference is an rvalue reference and
3343 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003344 // FIXME: C++ shouldn't be going through here! The rules are different
3345 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003346 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3347 // shouldn't be going through here!
Ted Kremenek35366a62009-07-17 17:50:17 +00003348 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003349 LHS = RT->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00003350 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003351 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003352
Eli Friedman3d815e72008-08-22 00:56:42 +00003353 QualType LHSCan = getCanonicalType(LHS),
3354 RHSCan = getCanonicalType(RHS);
3355
3356 // If two types are identical, they are compatible.
3357 if (LHSCan == RHSCan)
3358 return LHS;
3359
3360 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003361 // Note that we handle extended qualifiers later, in the
3362 // case for ExtQualType.
3363 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003364 return QualType();
3365
Eli Friedman852d63b2009-06-01 01:22:52 +00003366 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3367 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003368
Chris Lattner1adb8832008-01-14 05:45:46 +00003369 // We want to consider the two function types to be the same for these
3370 // comparisons, just force one to the other.
3371 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3372 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003373
Eli Friedman07d25872009-06-02 05:28:56 +00003374 // Strip off objc_gc attributes off the top level so they can be merged.
3375 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003376 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003377 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3378 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003379 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003380 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003381 // __strong attribue is redundant if other decl is an objective-c
3382 // object pointer (or decorated with __strong attribute); otherwise
3383 // issue error.
3384 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3385 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003386 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003387 return QualType();
3388
Eli Friedman07d25872009-06-02 05:28:56 +00003389 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3390 RHS.getCVRQualifiers());
3391 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003392 if (!Result.isNull()) {
3393 if (Result.getObjCGCAttr() == QualType::GCNone)
3394 Result = getObjCGCQualType(Result, GCAttr);
3395 else if (Result.getObjCGCAttr() != GCAttr)
3396 Result = QualType();
3397 }
Eli Friedman07d25872009-06-02 05:28:56 +00003398 return Result;
3399 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003400 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003401 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003402 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3403 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003404 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3405 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003406 // __strong attribue is redundant if other decl is an objective-c
3407 // object pointer (or decorated with __strong attribute); otherwise
3408 // issue error.
3409 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3410 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003411 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003412 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003413
Eli Friedman07d25872009-06-02 05:28:56 +00003414 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3415 LHS.getCVRQualifiers());
3416 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003417 if (!Result.isNull()) {
3418 if (Result.getObjCGCAttr() == QualType::GCNone)
3419 Result = getObjCGCQualType(Result, GCAttr);
3420 else if (Result.getObjCGCAttr() != GCAttr)
3421 Result = QualType();
3422 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003423 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003424 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003425 }
3426
Eli Friedman4c721d32008-02-12 08:23:06 +00003427 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003428 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3429 LHSClass = Type::ConstantArray;
3430 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3431 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003432
Nate Begeman213541a2008-04-18 23:10:10 +00003433 // Canonicalize ExtVector -> Vector.
3434 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3435 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003436
Chris Lattnerb0489812008-04-07 06:38:24 +00003437 // Consider qualified interfaces and interfaces the same.
Steve Naroff14108da2009-07-10 23:34:53 +00003438 // FIXME: Remove (ObjCObjectPointerType should obsolete this funny business).
Chris Lattnerb0489812008-04-07 06:38:24 +00003439 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3440 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003441
Chris Lattnera36a61f2008-04-07 05:43:21 +00003442 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003443 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003444 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3445 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003446 if (const EnumType* ETy = LHS->getAsEnumType()) {
3447 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3448 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003449 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003450 if (const EnumType* ETy = RHS->getAsEnumType()) {
3451 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3452 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003453 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003454
Eli Friedman3d815e72008-08-22 00:56:42 +00003455 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003456 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003457
Steve Naroff4a746782008-01-09 22:43:08 +00003458 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003459 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003460#define TYPE(Class, Base)
3461#define ABSTRACT_TYPE(Class, Base)
3462#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3463#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3464#include "clang/AST/TypeNodes.def"
3465 assert(false && "Non-canonical and dependent types shouldn't get here");
3466 return QualType();
3467
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003468 case Type::LValueReference:
3469 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003470 case Type::MemberPointer:
3471 assert(false && "C++ should never be in mergeTypes");
3472 return QualType();
3473
3474 case Type::IncompleteArray:
3475 case Type::VariableArray:
3476 case Type::FunctionProto:
3477 case Type::ExtVector:
3478 case Type::ObjCQualifiedInterface:
3479 assert(false && "Types are eliminated above");
3480 return QualType();
3481
Chris Lattner1adb8832008-01-14 05:45:46 +00003482 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003483 {
3484 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003485 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3486 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003487 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3488 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003489 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003490 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003491 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003492 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003493 return getPointerType(ResultType);
3494 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003495 case Type::BlockPointer:
3496 {
3497 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003498 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3499 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003500 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3501 if (ResultType.isNull()) return QualType();
3502 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3503 return LHS;
3504 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3505 return RHS;
3506 return getBlockPointerType(ResultType);
3507 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003508 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003509 {
3510 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3511 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3512 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3513 return QualType();
3514
3515 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3516 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3517 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3518 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003519 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3520 return LHS;
3521 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3522 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003523 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3524 ArrayType::ArraySizeModifier(), 0);
3525 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3526 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003527 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3528 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003529 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3530 return LHS;
3531 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3532 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003533 if (LVAT) {
3534 // FIXME: This isn't correct! But tricky to implement because
3535 // the array's size has to be the size of LHS, but the type
3536 // has to be different.
3537 return LHS;
3538 }
3539 if (RVAT) {
3540 // FIXME: This isn't correct! But tricky to implement because
3541 // the array's size has to be the size of RHS, but the type
3542 // has to be different.
3543 return RHS;
3544 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003545 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3546 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003547 return getIncompleteArrayType(ResultType,
3548 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003549 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003550 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003551 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003552 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003553 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003554 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003555 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003556 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003557 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003558 case Type::Complex:
3559 // Distinct complex types are incompatible.
3560 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003561 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003562 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003563 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3564 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003565 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003566 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003567 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003568 // FIXME: This should be type compatibility, e.g. whether
3569 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003570 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3571 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3572 if (LHSIface && RHSIface &&
3573 canAssignObjCInterfaces(LHSIface, RHSIface))
3574 return LHS;
3575
Eli Friedman3d815e72008-08-22 00:56:42 +00003576 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003577 }
Steve Naroff14108da2009-07-10 23:34:53 +00003578 case Type::ObjCObjectPointer: {
3579 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3580 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3581 return QualType();
3582
3583 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3584 RHS->getAsObjCObjectPointerType()))
3585 return LHS;
3586
Steve Naroffbc76dd02008-12-10 22:14:21 +00003587 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003588 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003589 case Type::FixedWidthInt:
3590 // Distinct fixed-width integers are not compatible.
3591 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003592 case Type::ExtQual:
3593 // FIXME: ExtQual types can be compatible even if they're not
3594 // identical!
3595 return QualType();
3596 // First attempt at an implementation, but I'm not really sure it's
3597 // right...
3598#if 0
3599 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3600 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3601 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3602 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3603 return QualType();
3604 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3605 LHSBase = QualType(LQual->getBaseType(), 0);
3606 RHSBase = QualType(RQual->getBaseType(), 0);
3607 ResultType = mergeTypes(LHSBase, RHSBase);
3608 if (ResultType.isNull()) return QualType();
3609 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3610 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3611 return LHS;
3612 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3613 return RHS;
3614 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3615 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3616 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3617 return ResultType;
3618#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003619
3620 case Type::TemplateSpecialization:
3621 assert(false && "Dependent types have no size");
3622 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003623 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003624
3625 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003626}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003627
Chris Lattner5426bf62008-04-07 07:01:58 +00003628//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003629// Integer Predicates
3630//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003631
Eli Friedmanad74a752008-06-28 06:23:08 +00003632unsigned ASTContext::getIntWidth(QualType T) {
3633 if (T == BoolTy)
3634 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003635 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3636 return FWIT->getWidth();
3637 }
3638 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003639 return (unsigned)getTypeSize(T);
3640}
3641
3642QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3643 assert(T->isSignedIntegerType() && "Unexpected type");
3644 if (const EnumType* ETy = T->getAsEnumType())
3645 T = ETy->getDecl()->getIntegerType();
3646 const BuiltinType* BTy = T->getAsBuiltinType();
3647 assert (BTy && "Unexpected signed integer type");
3648 switch (BTy->getKind()) {
3649 case BuiltinType::Char_S:
3650 case BuiltinType::SChar:
3651 return UnsignedCharTy;
3652 case BuiltinType::Short:
3653 return UnsignedShortTy;
3654 case BuiltinType::Int:
3655 return UnsignedIntTy;
3656 case BuiltinType::Long:
3657 return UnsignedLongTy;
3658 case BuiltinType::LongLong:
3659 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003660 case BuiltinType::Int128:
3661 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003662 default:
3663 assert(0 && "Unexpected signed integer type");
3664 return QualType();
3665 }
3666}
3667
Douglas Gregor2cf26342009-04-09 22:27:44 +00003668ExternalASTSource::~ExternalASTSource() { }
3669
3670void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003671
3672
3673//===----------------------------------------------------------------------===//
3674// Builtin Type Computation
3675//===----------------------------------------------------------------------===//
3676
3677/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3678/// pointer over the consumed characters. This returns the resultant type.
3679static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3680 ASTContext::GetBuiltinTypeError &Error,
3681 bool AllowTypeModifiers = true) {
3682 // Modifiers.
3683 int HowLong = 0;
3684 bool Signed = false, Unsigned = false;
3685
3686 // Read the modifiers first.
3687 bool Done = false;
3688 while (!Done) {
3689 switch (*Str++) {
3690 default: Done = true; --Str; break;
3691 case 'S':
3692 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3693 assert(!Signed && "Can't use 'S' modifier multiple times!");
3694 Signed = true;
3695 break;
3696 case 'U':
3697 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3698 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3699 Unsigned = true;
3700 break;
3701 case 'L':
3702 assert(HowLong <= 2 && "Can't have LLLL modifier");
3703 ++HowLong;
3704 break;
3705 }
3706 }
3707
3708 QualType Type;
3709
3710 // Read the base type.
3711 switch (*Str++) {
3712 default: assert(0 && "Unknown builtin type letter!");
3713 case 'v':
3714 assert(HowLong == 0 && !Signed && !Unsigned &&
3715 "Bad modifiers used with 'v'!");
3716 Type = Context.VoidTy;
3717 break;
3718 case 'f':
3719 assert(HowLong == 0 && !Signed && !Unsigned &&
3720 "Bad modifiers used with 'f'!");
3721 Type = Context.FloatTy;
3722 break;
3723 case 'd':
3724 assert(HowLong < 2 && !Signed && !Unsigned &&
3725 "Bad modifiers used with 'd'!");
3726 if (HowLong)
3727 Type = Context.LongDoubleTy;
3728 else
3729 Type = Context.DoubleTy;
3730 break;
3731 case 's':
3732 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3733 if (Unsigned)
3734 Type = Context.UnsignedShortTy;
3735 else
3736 Type = Context.ShortTy;
3737 break;
3738 case 'i':
3739 if (HowLong == 3)
3740 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3741 else if (HowLong == 2)
3742 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3743 else if (HowLong == 1)
3744 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3745 else
3746 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3747 break;
3748 case 'c':
3749 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3750 if (Signed)
3751 Type = Context.SignedCharTy;
3752 else if (Unsigned)
3753 Type = Context.UnsignedCharTy;
3754 else
3755 Type = Context.CharTy;
3756 break;
3757 case 'b': // boolean
3758 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3759 Type = Context.BoolTy;
3760 break;
3761 case 'z': // size_t.
3762 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3763 Type = Context.getSizeType();
3764 break;
3765 case 'F':
3766 Type = Context.getCFConstantStringType();
3767 break;
3768 case 'a':
3769 Type = Context.getBuiltinVaListType();
3770 assert(!Type.isNull() && "builtin va list type not initialized!");
3771 break;
3772 case 'A':
3773 // This is a "reference" to a va_list; however, what exactly
3774 // this means depends on how va_list is defined. There are two
3775 // different kinds of va_list: ones passed by value, and ones
3776 // passed by reference. An example of a by-value va_list is
3777 // x86, where va_list is a char*. An example of by-ref va_list
3778 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3779 // we want this argument to be a char*&; for x86-64, we want
3780 // it to be a __va_list_tag*.
3781 Type = Context.getBuiltinVaListType();
3782 assert(!Type.isNull() && "builtin va list type not initialized!");
3783 if (Type->isArrayType()) {
3784 Type = Context.getArrayDecayedType(Type);
3785 } else {
3786 Type = Context.getLValueReferenceType(Type);
3787 }
3788 break;
3789 case 'V': {
3790 char *End;
3791
3792 unsigned NumElements = strtoul(Str, &End, 10);
3793 assert(End != Str && "Missing vector size");
3794
3795 Str = End;
3796
3797 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3798 Type = Context.getVectorType(ElementType, NumElements);
3799 break;
3800 }
3801 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003802 Type = Context.getFILEType();
3803 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003804 Error = ASTContext::GE_Missing_FILE;
3805 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003806 } else {
3807 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003808 }
3809 }
3810 }
3811
3812 if (!AllowTypeModifiers)
3813 return Type;
3814
3815 Done = false;
3816 while (!Done) {
3817 switch (*Str++) {
3818 default: Done = true; --Str; break;
3819 case '*':
3820 Type = Context.getPointerType(Type);
3821 break;
3822 case '&':
3823 Type = Context.getLValueReferenceType(Type);
3824 break;
3825 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3826 case 'C':
3827 Type = Type.getQualifiedType(QualType::Const);
3828 break;
3829 }
3830 }
3831
3832 return Type;
3833}
3834
3835/// GetBuiltinType - Return the type for the specified builtin.
3836QualType ASTContext::GetBuiltinType(unsigned id,
3837 GetBuiltinTypeError &Error) {
3838 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3839
3840 llvm::SmallVector<QualType, 8> ArgTypes;
3841
3842 Error = GE_None;
3843 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3844 if (Error != GE_None)
3845 return QualType();
3846 while (TypeStr[0] && TypeStr[0] != '.') {
3847 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3848 if (Error != GE_None)
3849 return QualType();
3850
3851 // Do array -> pointer decay. The builtin should use the decayed type.
3852 if (Ty->isArrayType())
3853 Ty = getArrayDecayedType(Ty);
3854
3855 ArgTypes.push_back(Ty);
3856 }
3857
3858 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3859 "'.' should only occur at end of builtin type list!");
3860
3861 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3862 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3863 return getFunctionNoProtoType(ResType);
3864 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3865 TypeStr[0] == '.', 0);
3866}