blob: dbac120d262a91e1ee41cb332fffb695c667c73d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner61710852008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000036 Builtin::Context &builtins,
37 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000038 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Douglas Gregorc29f77b2009-07-07 16:35:42 +000039 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
40 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000041 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
42 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000043 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000044 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000045 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000046 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000047}
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049ASTContext::~ASTContext() {
50 // Deallocate all the types.
51 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000052 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000053 Types.pop_back();
54 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000055
Nuno Lopesb74668e2008-12-17 22:30:25 +000056 {
57 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
58 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
59 while (I != E) {
60 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
61 delete R;
62 }
63 }
64
65 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000066 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
67 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000068 while (I != E) {
69 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
70 delete R;
71 }
72 }
73
Douglas Gregorab452ba2009-03-26 23:50:42 +000074 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000075 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
76 NNS = NestedNameSpecifiers.begin(),
77 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000078 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000079 /* Increment in loop */)
80 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000081
82 if (GlobalNestedNameSpecifier)
83 GlobalNestedNameSpecifier->Destroy(*this);
84
Eli Friedmanb26153c2008-05-27 03:08:09 +000085 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
87
Douglas Gregor2cf26342009-04-09 22:27:44 +000088void
89ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
90 ExternalSource.reset(Source.take());
91}
92
Reid Spencer5f016e22007-07-11 17:01:13 +000093void ASTContext::PrintStats() const {
94 fprintf(stderr, "*** AST Context Stats:\n");
95 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000096
Douglas Gregordbe833d2009-05-26 14:40:08 +000097 unsigned counts[] = {
98#define TYPE(Name, Parent) 0,
99#define ABSTRACT_TYPE(Name, Parent)
100#include "clang/AST/TypeNodes.def"
101 0 // Extra
102 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000103
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
105 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000106 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
108
Douglas Gregordbe833d2009-05-26 14:40:08 +0000109 unsigned Idx = 0;
110 unsigned TotalBytes = 0;
111#define TYPE(Name, Parent) \
112 if (counts[Idx]) \
113 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
114 TotalBytes += counts[Idx] * sizeof(Name##Type); \
115 ++Idx;
116#define ABSTRACT_TYPE(Name, Parent)
117#include "clang/AST/TypeNodes.def"
118
119 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000120
121 if (ExternalSource.get()) {
122 fprintf(stderr, "\n");
123 ExternalSource->PrintStats();
124 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000125}
126
127
128void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000129 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000130}
131
Reid Spencer5f016e22007-07-11 17:01:13 +0000132void ASTContext::InitBuiltinTypes() {
133 assert(VoidTy.isNull() && "Context reinitialized?");
134
135 // C99 6.2.5p19.
136 InitBuiltinType(VoidTy, BuiltinType::Void);
137
138 // C99 6.2.5p2.
139 InitBuiltinType(BoolTy, BuiltinType::Bool);
140 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000141 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 InitBuiltinType(CharTy, BuiltinType::Char_S);
143 else
144 InitBuiltinType(CharTy, BuiltinType::Char_U);
145 // C99 6.2.5p4.
146 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
147 InitBuiltinType(ShortTy, BuiltinType::Short);
148 InitBuiltinType(IntTy, BuiltinType::Int);
149 InitBuiltinType(LongTy, BuiltinType::Long);
150 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
151
152 // C99 6.2.5p6.
153 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
154 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
155 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
156 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
157 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
158
159 // C99 6.2.5p10.
160 InitBuiltinType(FloatTy, BuiltinType::Float);
161 InitBuiltinType(DoubleTy, BuiltinType::Double);
162 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000163
Chris Lattner2df9ced2009-04-30 02:43:43 +0000164 // GNU extension, 128-bit integers.
165 InitBuiltinType(Int128Ty, BuiltinType::Int128);
166 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
167
Chris Lattner3a250322009-02-26 23:43:47 +0000168 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
169 InitBuiltinType(WCharTy, BuiltinType::WChar);
170 else // C99
171 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000172
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000174 InitBuiltinType(OverloadTy, BuiltinType::Overload);
175
176 // Placeholder type for type-dependent expressions whose type is
177 // completely unknown. No code should ever check a type against
178 // DependentTy and users should never see it; however, it is here to
179 // help diagnose failures to properly check for type-dependent
180 // expressions.
181 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182
Anders Carlssone89d1592009-06-26 18:41:36 +0000183 // Placeholder type for C++0x auto declarations whose real type has
184 // not yet been deduced.
185 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 // C99 6.2.5p11.
188 FloatComplexTy = getComplexType(FloatTy);
189 DoubleComplexTy = getComplexType(DoubleTy);
190 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000191
Steve Naroff7e219e42007-10-15 14:41:52 +0000192 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000193
Steve Naroff14108da2009-07-10 23:34:53 +0000194 ObjCIdType = QualType();
195 ObjCClassType = QualType();
196
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000198
199 // void * type
200 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000201
202 // nullptr type (C++0x 2.14.7)
203 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
Douglas Gregor2e222532009-07-02 17:08:52 +0000206namespace {
207 class BeforeInTranslationUnit
208 : std::binary_function<SourceRange, SourceRange, bool> {
209 SourceManager *SourceMgr;
210
211 public:
212 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
213
214 bool operator()(SourceRange X, SourceRange Y) {
215 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
216 }
217 };
218}
219
220/// \brief Determine whether the given comment is a Doxygen-style comment.
221///
222/// \param Start the start of the comment text.
223///
224/// \param End the end of the comment text.
225///
226/// \param Member whether we want to check whether this is a member comment
227/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
228/// we only return true when we find a non-member comment.
229static bool
230isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
231 bool Member = false) {
232 const char *BufferStart
233 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
234 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
235 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
236
237 if (End - Start < 4)
238 return false;
239
240 assert(Start[0] == '/' && "Not a comment?");
241 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
242 return false;
243 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
244 return false;
245
246 return (Start[3] == '<') == Member;
247}
248
249/// \brief Retrieve the comment associated with the given declaration, if
250/// it has one.
251const char *ASTContext::getCommentForDecl(const Decl *D) {
252 if (!D)
253 return 0;
254
255 // Check whether we have cached a comment string for this declaration
256 // already.
257 llvm::DenseMap<const Decl *, std::string>::iterator Pos
258 = DeclComments.find(D);
259 if (Pos != DeclComments.end())
260 return Pos->second.c_str();
261
262 // If we have an external AST source and have not yet loaded comments from
263 // that source, do so now.
264 if (ExternalSource && !LoadedExternalComments) {
265 std::vector<SourceRange> LoadedComments;
266 ExternalSource->ReadComments(LoadedComments);
267
268 if (!LoadedComments.empty())
269 Comments.insert(Comments.begin(), LoadedComments.begin(),
270 LoadedComments.end());
271
272 LoadedExternalComments = true;
273 }
274
275 // If there are no comments anywhere, we won't find anything.
276 if (Comments.empty())
277 return 0;
278
279 // If the declaration doesn't map directly to a location in a file, we
280 // can't find the comment.
281 SourceLocation DeclStartLoc = D->getLocStart();
282 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
283 return 0;
284
285 // Find the comment that occurs just before this declaration.
286 std::vector<SourceRange>::iterator LastComment
287 = std::lower_bound(Comments.begin(), Comments.end(),
288 SourceRange(DeclStartLoc),
289 BeforeInTranslationUnit(&SourceMgr));
290
291 // Decompose the location for the start of the declaration and find the
292 // beginning of the file buffer.
293 std::pair<FileID, unsigned> DeclStartDecomp
294 = SourceMgr.getDecomposedLoc(DeclStartLoc);
295 const char *FileBufferStart
296 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
297
298 // First check whether we have a comment for a member.
299 if (LastComment != Comments.end() &&
300 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
301 isDoxygenComment(SourceMgr, *LastComment, true)) {
302 std::pair<FileID, unsigned> LastCommentEndDecomp
303 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
304 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
305 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
306 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
307 LastCommentEndDecomp.second)) {
308 // The Doxygen member comment comes after the declaration starts and
309 // is on the same line and in the same file as the declaration. This
310 // is the comment we want.
311 std::string &Result = DeclComments[D];
312 Result.append(FileBufferStart +
313 SourceMgr.getFileOffset(LastComment->getBegin()),
314 FileBufferStart + LastCommentEndDecomp.second + 1);
315 return Result.c_str();
316 }
317 }
318
319 if (LastComment == Comments.begin())
320 return 0;
321 --LastComment;
322
323 // Decompose the end of the comment.
324 std::pair<FileID, unsigned> LastCommentEndDecomp
325 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
326
327 // If the comment and the declaration aren't in the same file, then they
328 // aren't related.
329 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
330 return 0;
331
332 // Check that we actually have a Doxygen comment.
333 if (!isDoxygenComment(SourceMgr, *LastComment))
334 return 0;
335
336 // Compute the starting line for the declaration and for the end of the
337 // comment (this is expensive).
338 unsigned DeclStartLine
339 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
340 unsigned CommentEndLine
341 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
342 LastCommentEndDecomp.second);
343
344 // If the comment does not end on the line prior to the declaration, then
345 // the comment is not associated with the declaration at all.
346 if (CommentEndLine + 1 != DeclStartLine)
347 return 0;
348
349 // We have a comment, but there may be more comments on the previous lines.
350 // Keep looking so long as the comments are still Doxygen comments and are
351 // still adjacent.
352 unsigned ExpectedLine
353 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
354 std::vector<SourceRange>::iterator FirstComment = LastComment;
355 while (FirstComment != Comments.begin()) {
356 // Look at the previous comment
357 --FirstComment;
358 std::pair<FileID, unsigned> Decomp
359 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
360
361 // If this previous comment is in a different file, we're done.
362 if (Decomp.first != DeclStartDecomp.first) {
363 ++FirstComment;
364 break;
365 }
366
367 // If this comment is not a Doxygen comment, we're done.
368 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
369 ++FirstComment;
370 break;
371 }
372
373 // If the line number is not what we expected, we're done.
374 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
375 if (Line != ExpectedLine) {
376 ++FirstComment;
377 break;
378 }
379
380 // Set the next expected line number.
381 ExpectedLine
382 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
383 }
384
385 // The iterator range [FirstComment, LastComment] contains all of the
386 // BCPL comments that, together, are associated with this declaration.
387 // Form a single comment block string for this declaration that concatenates
388 // all of these comments.
389 std::string &Result = DeclComments[D];
390 while (FirstComment != LastComment) {
391 std::pair<FileID, unsigned> DecompStart
392 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
393 std::pair<FileID, unsigned> DecompEnd
394 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
395 Result.append(FileBufferStart + DecompStart.second,
396 FileBufferStart + DecompEnd.second + 1);
397 ++FirstComment;
398 }
399
400 // Append the last comment line.
401 Result.append(FileBufferStart +
402 SourceMgr.getFileOffset(LastComment->getBegin()),
403 FileBufferStart + LastCommentEndDecomp.second + 1);
404 return Result.c_str();
405}
406
Chris Lattner464175b2007-07-18 17:52:12 +0000407//===----------------------------------------------------------------------===//
408// Type Sizing and Analysis
409//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000410
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000411/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
412/// scalar floating point type.
413const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
414 const BuiltinType *BT = T->getAsBuiltinType();
415 assert(BT && "Not a floating point type!");
416 switch (BT->getKind()) {
417 default: assert(0 && "Not a floating point type!");
418 case BuiltinType::Float: return Target.getFloatFormat();
419 case BuiltinType::Double: return Target.getDoubleFormat();
420 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
421 }
422}
423
Chris Lattneraf707ab2009-01-24 21:53:27 +0000424/// getDeclAlign - Return a conservative estimate of the alignment of the
425/// specified decl. Note that bitfields do not have a valid alignment, so
426/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000427unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000428 unsigned Align = Target.getCharWidth();
429
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000430 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000431 Align = std::max(Align, AA->getAlignment());
432
Chris Lattneraf707ab2009-01-24 21:53:27 +0000433 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
434 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000435 if (const ReferenceType* RT = T->getAsReferenceType()) {
436 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000437 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000438 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
439 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000440 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
441 T = cast<ArrayType>(T)->getElementType();
442
443 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
444 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000445 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000446
447 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000448}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000449
Chris Lattnera7674d82007-07-13 22:13:22 +0000450/// getTypeSize - Return the size of the specified type, in bits. This method
451/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000452std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000453ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000454 uint64_t Width=0;
455 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000456 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000457#define TYPE(Class, Base)
458#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000459#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000460#define DEPENDENT_TYPE(Class, Base) case Type::Class:
461#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000462 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000463 break;
464
Chris Lattner692233e2007-07-13 22:27:08 +0000465 case Type::FunctionNoProto:
466 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000467 // GCC extension: alignof(function) = 32 bits
468 Width = 0;
469 Align = 32;
470 break;
471
Douglas Gregor72564e72009-02-26 23:50:07 +0000472 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000473 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000474 Width = 0;
475 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
476 break;
477
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000478 case Type::ConstantArrayWithExpr:
479 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000480 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000481 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000482
Chris Lattner98be4942008-03-05 18:54:05 +0000483 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000484 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000485 Align = EltInfo.second;
486 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000487 }
Nate Begeman213541a2008-04-18 23:10:10 +0000488 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000489 case Type::Vector: {
490 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000491 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000492 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000493 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000494 // If the alignment is not a power of 2, round up to the next power of 2.
495 // This happens for non-power-of-2 length vectors.
496 // FIXME: this should probably be a target property.
497 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000498 break;
499 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000500
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000501 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000502 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000503 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000504 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000505 // GCC extension: alignof(void) = 8 bits.
506 Width = 0;
507 Align = 8;
508 break;
509
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000510 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000511 Width = Target.getBoolWidth();
512 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000513 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000514 case BuiltinType::Char_S:
515 case BuiltinType::Char_U:
516 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000517 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000518 Width = Target.getCharWidth();
519 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000520 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000521 case BuiltinType::WChar:
522 Width = Target.getWCharWidth();
523 Align = Target.getWCharAlign();
524 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000525 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000526 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000527 Width = Target.getShortWidth();
528 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000529 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000530 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000531 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000532 Width = Target.getIntWidth();
533 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000534 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000535 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000536 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000537 Width = Target.getLongWidth();
538 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000539 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000540 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000541 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000542 Width = Target.getLongLongWidth();
543 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000544 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000545 case BuiltinType::Int128:
546 case BuiltinType::UInt128:
547 Width = 128;
548 Align = 128; // int128_t is 128-bit aligned on all targets.
549 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000550 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000551 Width = Target.getFloatWidth();
552 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000553 break;
554 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000555 Width = Target.getDoubleWidth();
556 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000557 break;
558 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000559 Width = Target.getLongDoubleWidth();
560 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000561 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000562 case BuiltinType::NullPtr:
563 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
564 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000565 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000566 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000567 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000568 case Type::FixedWidthInt:
569 // FIXME: This isn't precisely correct; the width/alignment should depend
570 // on the available types for the target
571 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000572 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000573 Align = Width;
574 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000575 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000576 // FIXME: Pointers into different addr spaces could have different sizes and
577 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000578 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000579 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000580 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000581 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000582 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000583 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000584 case Type::BlockPointer: {
585 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
586 Width = Target.getPointerWidth(AS);
587 Align = Target.getPointerAlign(AS);
588 break;
589 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000590 case Type::Pointer: {
591 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000592 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000593 Align = Target.getPointerAlign(AS);
594 break;
595 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000596 case Type::LValueReference:
597 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000598 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000599 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000600 // FIXME: This is wrong for struct layout: a reference in a struct has
601 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000602 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000603 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000604 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
605 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
606 // If we ever want to support other ABIs this needs to be abstracted.
607
Sebastian Redlf30208a2009-01-24 21:16:55 +0000608 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000609 std::pair<uint64_t, unsigned> PtrDiffInfo =
610 getTypeInfo(getPointerDiffType());
611 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000612 if (Pointee->isFunctionType())
613 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000614 Align = PtrDiffInfo.second;
615 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000616 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000617 case Type::Complex: {
618 // Complex types have the same alignment as their elements, but twice the
619 // size.
620 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000621 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000623 Align = EltInfo.second;
624 break;
625 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000626 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000627 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000628 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
629 Width = Layout.getSize();
630 Align = Layout.getAlignment();
631 break;
632 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000633 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000634 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000635 const TagType *TT = cast<TagType>(T);
636
637 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000638 Width = 1;
639 Align = 1;
640 break;
641 }
642
Daniel Dunbar1d751182008-11-08 05:48:37 +0000643 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000644 return getTypeInfo(ET->getDecl()->getIntegerType());
645
Daniel Dunbar1d751182008-11-08 05:48:37 +0000646 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000647 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
648 Width = Layout.getSize();
649 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000650 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000651 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000652
Douglas Gregor18857642009-04-30 17:32:17 +0000653 case Type::Typedef: {
654 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000655 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000656 Align = Aligned->getAlignment();
657 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
658 } else
659 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000660 break;
Chris Lattner71763312008-04-06 22:05:18 +0000661 }
Douglas Gregor18857642009-04-30 17:32:17 +0000662
663 case Type::TypeOfExpr:
664 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
665 .getTypePtr());
666
667 case Type::TypeOf:
668 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
669
Anders Carlsson395b4752009-06-24 19:06:50 +0000670 case Type::Decltype:
671 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
672 .getTypePtr());
673
Douglas Gregor18857642009-04-30 17:32:17 +0000674 case Type::QualifiedName:
675 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
676
677 case Type::TemplateSpecialization:
678 assert(getCanonicalType(T) != T &&
679 "Cannot request the size of a dependent type");
680 // FIXME: this is likely to be wrong once we support template
681 // aliases, since a template alias could refer to a typedef that
682 // has an __aligned__ attribute on it.
683 return getTypeInfo(getCanonicalType(T));
684 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000685
Chris Lattner464175b2007-07-18 17:52:12 +0000686 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000687 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000688}
689
Chris Lattner34ebde42009-01-27 18:08:34 +0000690/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
691/// type for the current target in bits. This can be different than the ABI
692/// alignment in cases where it is beneficial for performance to overalign
693/// a data type.
694unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
695 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000696
697 // Double and long long should be naturally aligned if possible.
698 if (const ComplexType* CT = T->getAsComplexType())
699 T = CT->getElementType().getTypePtr();
700 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
701 T->isSpecificBuiltinType(BuiltinType::LongLong))
702 return std::max(ABIAlign, (unsigned)getTypeSize(T));
703
Chris Lattner34ebde42009-01-27 18:08:34 +0000704 return ABIAlign;
705}
706
707
Devang Patel8b277042008-06-04 21:22:16 +0000708/// LayoutField - Field layout.
709void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000710 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000711 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000712 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000713 uint64_t FieldOffset = IsUnion ? 0 : Size;
714 uint64_t FieldSize;
715 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000716
717 // FIXME: Should this override struct packing? Probably we want to
718 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000719 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000720 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000721
722 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
723 // TODO: Need to check this algorithm on other targets!
724 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000725 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000726
727 std::pair<uint64_t, unsigned> FieldInfo =
728 Context.getTypeInfo(FD->getType());
729 uint64_t TypeSize = FieldInfo.first;
730
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000731 // Determine the alignment of this bitfield. The packing
732 // attributes define a maximum and the alignment attribute defines
733 // a minimum.
734 // FIXME: What is the right behavior when the specified alignment
735 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000736 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000737 if (FieldPacking)
738 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000739 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000740 FieldAlign = std::max(FieldAlign, AA->getAlignment());
741
742 // Check if we need to add padding to give the field the correct
743 // alignment.
744 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
745 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
746
747 // Padding members don't affect overall alignment
748 if (!FD->getIdentifier())
749 FieldAlign = 1;
750 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000751 if (FD->getType()->isIncompleteArrayType()) {
752 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000753 // query getTypeInfo about these, so we figure it out here.
754 // Flexible array members don't have any size, but they
755 // have to be aligned appropriately for their element type.
756 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000757 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000758 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000759 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
760 unsigned AS = RT->getPointeeType().getAddressSpace();
761 FieldSize = Context.Target.getPointerWidth(AS);
762 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000763 } else {
764 std::pair<uint64_t, unsigned> FieldInfo =
765 Context.getTypeInfo(FD->getType());
766 FieldSize = FieldInfo.first;
767 FieldAlign = FieldInfo.second;
768 }
769
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000770 // Determine the alignment of this bitfield. The packing
771 // attributes define a maximum and the alignment attribute defines
772 // a minimum. Additionally, the packing alignment must be at least
773 // a byte for non-bitfields.
774 //
775 // FIXME: What is the right behavior when the specified alignment
776 // is smaller than the specified packing?
777 if (FieldPacking)
778 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000779 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000780 FieldAlign = std::max(FieldAlign, AA->getAlignment());
781
782 // Round up the current record size to the field's alignment boundary.
783 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
784 }
785
786 // Place this field at the current location.
787 FieldOffsets[FieldNo] = FieldOffset;
788
789 // Reserve space for this field.
790 if (IsUnion) {
791 Size = std::max(Size, FieldSize);
792 } else {
793 Size = FieldOffset + FieldSize;
794 }
795
Daniel Dunbard6884a02009-05-04 05:16:21 +0000796 // Remember the next available offset.
797 NextOffset = Size;
798
Devang Patel8b277042008-06-04 21:22:16 +0000799 // Remember max struct/class alignment.
800 Alignment = std::max(Alignment, FieldAlign);
801}
802
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000803static void CollectLocalObjCIvars(ASTContext *Ctx,
804 const ObjCInterfaceDecl *OI,
805 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000806 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
807 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000808 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000809 if (!IVDecl->isInvalidDecl())
810 Fields.push_back(cast<FieldDecl>(IVDecl));
811 }
812}
813
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000814void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
815 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
816 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
817 CollectObjCIvars(SuperClass, Fields);
818 CollectLocalObjCIvars(this, OI, Fields);
819}
820
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000821/// ShallowCollectObjCIvars -
822/// Collect all ivars, including those synthesized, in the current class.
823///
824void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
825 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
826 bool CollectSynthesized) {
827 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
828 E = OI->ivar_end(); I != E; ++I) {
829 Ivars.push_back(*I);
830 }
831 if (CollectSynthesized)
832 CollectSynthesizedIvars(OI, Ivars);
833}
834
Fariborz Jahanian98200742009-05-12 18:14:29 +0000835void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
836 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000837 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
838 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000839 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
840 Ivars.push_back(Ivar);
841
842 // Also look into nested protocols.
843 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
844 E = PD->protocol_end(); P != E; ++P)
845 CollectProtocolSynthesizedIvars(*P, Ivars);
846}
847
848/// CollectSynthesizedIvars -
849/// This routine collect synthesized ivars for the designated class.
850///
851void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
852 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000853 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
854 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000855 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
856 Ivars.push_back(Ivar);
857 }
858 // Also look into interface's protocol list for properties declared
859 // in the protocol and whose ivars are synthesized.
860 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
861 PE = OI->protocol_end(); P != PE; ++P) {
862 ObjCProtocolDecl *PD = (*P);
863 CollectProtocolSynthesizedIvars(PD, Ivars);
864 }
865}
866
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000867unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
868 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000869 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
870 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000871 if ((*I)->getPropertyIvarDecl())
872 ++count;
873
874 // Also look into nested protocols.
875 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
876 E = PD->protocol_end(); P != E; ++P)
877 count += CountProtocolSynthesizedIvars(*P);
878 return count;
879}
880
881unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
882{
883 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000884 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
885 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000886 if ((*I)->getPropertyIvarDecl())
887 ++count;
888 }
889 // Also look into interface's protocol list for properties declared
890 // in the protocol and whose ivars are synthesized.
891 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
892 PE = OI->protocol_end(); P != PE; ++P) {
893 ObjCProtocolDecl *PD = (*P);
894 count += CountProtocolSynthesizedIvars(PD);
895 }
896 return count;
897}
898
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000899/// getInterfaceLayoutImpl - Get or compute information about the
900/// layout of the given interface.
901///
902/// \param Impl - If given, also include the layout of the interface's
903/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000904const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000905ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
906 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000907 assert(!D->isForwardDecl() && "Invalid interface decl!");
908
Devang Patel44a3dde2008-06-04 21:54:36 +0000909 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000910 ObjCContainerDecl *Key =
911 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
912 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
913 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000914
Daniel Dunbar453addb2009-05-03 11:16:44 +0000915 unsigned FieldCount = D->ivar_size();
916 // Add in synthesized ivar count if laying out an implementation.
917 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000918 unsigned SynthCount = CountSynthesizedIvars(D);
919 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000920 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000921 // entry. Note we can't cache this because we simply free all
922 // entries later; however we shouldn't look up implementations
923 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000924 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000925 return getObjCLayout(D, 0);
926 }
927
Devang Patel6a5a34c2008-06-06 02:14:01 +0000928 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000929 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000930 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
931 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000932
Daniel Dunbar913af352009-05-07 21:58:26 +0000933 // We start laying out ivars not at the end of the superclass
934 // structure, but at the next byte following the last field.
935 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000936
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000937 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000938 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000939 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000940 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000941 NewEntry->InitializeLayout(FieldCount);
942 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000943
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000944 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000945 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000946 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000947
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000948 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000949 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
950 AA->getAlignment()));
951
952 // Layout each ivar sequentially.
953 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000954 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
955 ShallowCollectObjCIvars(D, Ivars, Impl);
956 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
957 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
958
Devang Patel44a3dde2008-06-04 21:54:36 +0000959 // Finally, round the size of the total struct up to the alignment of the
960 // struct itself.
961 NewEntry->FinalizeLayout();
962 return *NewEntry;
963}
964
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000965const ASTRecordLayout &
966ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
967 return getObjCLayout(D, 0);
968}
969
970const ASTRecordLayout &
971ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
972 return getObjCLayout(D->getClassInterface(), D);
973}
974
Devang Patel88a981b2007-11-01 19:11:01 +0000975/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000976/// specified record (struct/union/class), which indicates its size and field
977/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000978const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000979 D = D->getDefinition(*this);
980 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000981
Chris Lattner464175b2007-07-18 17:52:12 +0000982 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000983 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000984 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000985
Devang Patel88a981b2007-11-01 19:11:01 +0000986 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
987 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
988 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000989 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000990
Douglas Gregore267ff32008-12-11 20:41:00 +0000991 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000992 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000993 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000994
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000995 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000996 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000997 StructPacking = PA->getAlignment();
998
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000999 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +00001000 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1001 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001002
Eli Friedman4bd998b2008-05-30 09:31:38 +00001003 // Layout each field, for now, just sequentially, respecting alignment. In
1004 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001005 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001006 for (RecordDecl::field_iterator Field = D->field_begin(),
1007 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001008 Field != FieldEnd; (void)++Field, ++FieldIdx)
1009 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001010
1011 // Finally, round the size of the total struct up to the alignment of the
1012 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001013 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001014 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001015}
1016
Chris Lattnera7674d82007-07-13 22:13:22 +00001017//===----------------------------------------------------------------------===//
1018// Type creation/memoization methods
1019//===----------------------------------------------------------------------===//
1020
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001021QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001022 QualType CanT = getCanonicalType(T);
1023 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001024 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001025
1026 // If we are composing extended qualifiers together, merge together into one
1027 // ExtQualType node.
1028 unsigned CVRQuals = T.getCVRQualifiers();
1029 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1030 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001031
Chris Lattnerb7d25532009-02-18 22:53:11 +00001032 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1033 // If this type already has an address space specified, it cannot get
1034 // another one.
1035 assert(EQT->getAddressSpace() == 0 &&
1036 "Type cannot be in multiple addr spaces!");
1037 GCAttr = EQT->getObjCGCAttr();
1038 TypeNode = EQT->getBaseType();
1039 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001040
Chris Lattnerb7d25532009-02-18 22:53:11 +00001041 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001042 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001043 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001044 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001045 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001046 return QualType(EXTQy, CVRQuals);
1047
Christopher Lambebb97e92008-02-04 02:31:56 +00001048 // If the base type isn't canonical, this won't be a canonical type either,
1049 // so fill in the canonical type field.
1050 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001051 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001052 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001053
Chris Lattnerb7d25532009-02-18 22:53:11 +00001054 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001055 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001056 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001057 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001058 ExtQualType *New =
1059 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001060 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001061 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001062 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001063}
1064
Chris Lattnerb7d25532009-02-18 22:53:11 +00001065QualType ASTContext::getObjCGCQualType(QualType T,
1066 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001067 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001068 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001069 return T;
1070
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001071 if (T->isPointerType()) {
1072 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00001073 if (Pointee->isPointerType() || Pointee->isObjCObjectPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001074 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1075 return getPointerType(ResultType);
1076 }
1077 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001078 // If we are composing extended qualifiers together, merge together into one
1079 // ExtQualType node.
1080 unsigned CVRQuals = T.getCVRQualifiers();
1081 Type *TypeNode = T.getTypePtr();
1082 unsigned AddressSpace = 0;
1083
1084 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1085 // If this type already has an address space specified, it cannot get
1086 // another one.
1087 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1088 "Type cannot be in multiple addr spaces!");
1089 AddressSpace = EQT->getAddressSpace();
1090 TypeNode = EQT->getBaseType();
1091 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001092
1093 // Check if we've already instantiated an gc qual'd type of this type.
1094 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001095 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001096 void *InsertPos = 0;
1097 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001098 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001099
1100 // If the base type isn't canonical, this won't be a canonical type either,
1101 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001102 // FIXME: Isn't this also not canonical if the base type is a array
1103 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001104 QualType Canonical;
1105 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001106 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001107
Chris Lattnerb7d25532009-02-18 22:53:11 +00001108 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001109 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1110 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1111 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001112 ExtQualType *New =
1113 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001114 ExtQualTypes.InsertNode(New, InsertPos);
1115 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001116 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001117}
Chris Lattnera7674d82007-07-13 22:13:22 +00001118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119/// getComplexType - Return the uniqued reference to the type for a complex
1120/// number with the specified element type.
1121QualType ASTContext::getComplexType(QualType T) {
1122 // Unique pointers, to guarantee there is only one pointer of a particular
1123 // structure.
1124 llvm::FoldingSetNodeID ID;
1125 ComplexType::Profile(ID, T);
1126
1127 void *InsertPos = 0;
1128 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1129 return QualType(CT, 0);
1130
1131 // If the pointee type isn't canonical, this won't be a canonical type either,
1132 // so fill in the canonical type field.
1133 QualType Canonical;
1134 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001135 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001136
1137 // Get the new insert position for the node we care about.
1138 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001139 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 }
Steve Narofff83820b2009-01-27 22:08:43 +00001141 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 Types.push_back(New);
1143 ComplexTypes.InsertNode(New, InsertPos);
1144 return QualType(New, 0);
1145}
1146
Eli Friedmanf98aba32009-02-13 02:31:07 +00001147QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1148 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1149 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1150 FixedWidthIntType *&Entry = Map[Width];
1151 if (!Entry)
1152 Entry = new FixedWidthIntType(Width, Signed);
1153 return QualType(Entry, 0);
1154}
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
1156/// getPointerType - Return the uniqued reference to the type for a pointer to
1157/// the specified type.
1158QualType ASTContext::getPointerType(QualType T) {
1159 // Unique pointers, to guarantee there is only one pointer of a particular
1160 // structure.
1161 llvm::FoldingSetNodeID ID;
1162 PointerType::Profile(ID, T);
1163
1164 void *InsertPos = 0;
1165 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1166 return QualType(PT, 0);
1167
1168 // If the pointee type isn't canonical, this won't be a canonical type either,
1169 // so fill in the canonical type field.
1170 QualType Canonical;
1171 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001172 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 // Get the new insert position for the node we care about.
1175 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001176 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 }
Steve Narofff83820b2009-01-27 22:08:43 +00001178 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 Types.push_back(New);
1180 PointerTypes.InsertNode(New, InsertPos);
1181 return QualType(New, 0);
1182}
1183
Steve Naroff5618bd42008-08-27 16:04:49 +00001184/// getBlockPointerType - Return the uniqued reference to the type for
1185/// a pointer to the specified block.
1186QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001187 assert(T->isFunctionType() && "block of function types only");
1188 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001189 // structure.
1190 llvm::FoldingSetNodeID ID;
1191 BlockPointerType::Profile(ID, T);
1192
1193 void *InsertPos = 0;
1194 if (BlockPointerType *PT =
1195 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1196 return QualType(PT, 0);
1197
Steve Naroff296e8d52008-08-28 19:20:44 +00001198 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001199 // type either so fill in the canonical type field.
1200 QualType Canonical;
1201 if (!T->isCanonical()) {
1202 Canonical = getBlockPointerType(getCanonicalType(T));
1203
1204 // Get the new insert position for the node we care about.
1205 BlockPointerType *NewIP =
1206 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001207 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001208 }
Steve Narofff83820b2009-01-27 22:08:43 +00001209 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001210 Types.push_back(New);
1211 BlockPointerTypes.InsertNode(New, InsertPos);
1212 return QualType(New, 0);
1213}
1214
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001215/// getLValueReferenceType - Return the uniqued reference to the type for an
1216/// lvalue reference to the specified type.
1217QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // Unique pointers, to guarantee there is only one pointer of a particular
1219 // structure.
1220 llvm::FoldingSetNodeID ID;
1221 ReferenceType::Profile(ID, T);
1222
1223 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001224 if (LValueReferenceType *RT =
1225 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 // If the referencee type isn't canonical, this won't be a canonical type
1229 // either, so fill in the canonical type field.
1230 QualType Canonical;
1231 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001232 Canonical = getLValueReferenceType(getCanonicalType(T));
1233
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001235 LValueReferenceType *NewIP =
1236 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001237 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 }
1239
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001240 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001242 LValueReferenceTypes.InsertNode(New, InsertPos);
1243 return QualType(New, 0);
1244}
1245
1246/// getRValueReferenceType - Return the uniqued reference to the type for an
1247/// rvalue reference to the specified type.
1248QualType ASTContext::getRValueReferenceType(QualType T) {
1249 // Unique pointers, to guarantee there is only one pointer of a particular
1250 // structure.
1251 llvm::FoldingSetNodeID ID;
1252 ReferenceType::Profile(ID, T);
1253
1254 void *InsertPos = 0;
1255 if (RValueReferenceType *RT =
1256 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1257 return QualType(RT, 0);
1258
1259 // If the referencee type isn't canonical, this won't be a canonical type
1260 // either, so fill in the canonical type field.
1261 QualType Canonical;
1262 if (!T->isCanonical()) {
1263 Canonical = getRValueReferenceType(getCanonicalType(T));
1264
1265 // Get the new insert position for the node we care about.
1266 RValueReferenceType *NewIP =
1267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1269 }
1270
1271 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1272 Types.push_back(New);
1273 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 return QualType(New, 0);
1275}
1276
Sebastian Redlf30208a2009-01-24 21:16:55 +00001277/// getMemberPointerType - Return the uniqued reference to the type for a
1278/// member pointer to the specified type, in the specified class.
1279QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1280{
1281 // Unique pointers, to guarantee there is only one pointer of a particular
1282 // structure.
1283 llvm::FoldingSetNodeID ID;
1284 MemberPointerType::Profile(ID, T, Cls);
1285
1286 void *InsertPos = 0;
1287 if (MemberPointerType *PT =
1288 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1289 return QualType(PT, 0);
1290
1291 // If the pointee or class type isn't canonical, this won't be a canonical
1292 // type either, so fill in the canonical type field.
1293 QualType Canonical;
1294 if (!T->isCanonical()) {
1295 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1296
1297 // Get the new insert position for the node we care about.
1298 MemberPointerType *NewIP =
1299 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1300 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1301 }
Steve Narofff83820b2009-01-27 22:08:43 +00001302 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001303 Types.push_back(New);
1304 MemberPointerTypes.InsertNode(New, InsertPos);
1305 return QualType(New, 0);
1306}
1307
Steve Narofffb22d962007-08-30 01:06:46 +00001308/// getConstantArrayType - Return the unique reference to the type for an
1309/// array of the specified element type.
1310QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001311 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001312 ArrayType::ArraySizeModifier ASM,
1313 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001314 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1315 "Constant array of VLAs is illegal!");
1316
Chris Lattner38aeec72009-05-13 04:12:56 +00001317 // Convert the array size into a canonical width matching the pointer size for
1318 // the target.
1319 llvm::APInt ArySize(ArySizeIn);
1320 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1321
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001323 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001324
1325 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001326 if (ConstantArrayType *ATP =
1327 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 return QualType(ATP, 0);
1329
1330 // If the element type isn't canonical, this won't be a canonical type either,
1331 // so fill in the canonical type field.
1332 QualType Canonical;
1333 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001334 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001335 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001337 ConstantArrayType *NewIP =
1338 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001339 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 }
1341
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001342 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001343 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001344 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 Types.push_back(New);
1346 return QualType(New, 0);
1347}
1348
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001349/// getConstantArrayWithExprType - Return a reference to the type for
1350/// an array of the specified element type.
1351QualType
1352ASTContext::getConstantArrayWithExprType(QualType EltTy,
1353 const llvm::APInt &ArySizeIn,
1354 Expr *ArySizeExpr,
1355 ArrayType::ArraySizeModifier ASM,
1356 unsigned EltTypeQuals,
1357 SourceRange Brackets) {
1358 // Convert the array size into a canonical width matching the pointer
1359 // size for the target.
1360 llvm::APInt ArySize(ArySizeIn);
1361 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1362
1363 // Compute the canonical ConstantArrayType.
1364 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1365 ArySize, ASM, EltTypeQuals);
1366 // Since we don't unique expressions, it isn't possible to unique VLA's
1367 // that have an expression provided for their size.
1368 ConstantArrayWithExprType *New =
1369 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1370 ArySize, ArySizeExpr,
1371 ASM, EltTypeQuals, Brackets);
1372 Types.push_back(New);
1373 return QualType(New, 0);
1374}
1375
1376/// getConstantArrayWithoutExprType - Return a reference to the type for
1377/// an array of the specified element type.
1378QualType
1379ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1380 const llvm::APInt &ArySizeIn,
1381 ArrayType::ArraySizeModifier ASM,
1382 unsigned EltTypeQuals) {
1383 // Convert the array size into a canonical width matching the pointer
1384 // size for the target.
1385 llvm::APInt ArySize(ArySizeIn);
1386 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1387
1388 // Compute the canonical ConstantArrayType.
1389 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1390 ArySize, ASM, EltTypeQuals);
1391 ConstantArrayWithoutExprType *New =
1392 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1393 ArySize, ASM, EltTypeQuals);
1394 Types.push_back(New);
1395 return QualType(New, 0);
1396}
1397
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001398/// getVariableArrayType - Returns a non-unique reference to the type for a
1399/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001400QualType ASTContext::getVariableArrayType(QualType EltTy,
1401 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001402 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001403 unsigned EltTypeQuals,
1404 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001405 // Since we don't unique expressions, it isn't possible to unique VLA's
1406 // that have an expression provided for their size.
1407
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001408 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001409 new(*this,8)VariableArrayType(EltTy, QualType(),
1410 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001411
1412 VariableArrayTypes.push_back(New);
1413 Types.push_back(New);
1414 return QualType(New, 0);
1415}
1416
Douglas Gregor898574e2008-12-05 23:32:09 +00001417/// getDependentSizedArrayType - Returns a non-unique reference to
1418/// the type for a dependently-sized array of the specified element
1419/// type. FIXME: We will need these to be uniqued, or at least
1420/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001421QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1422 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001423 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001424 unsigned EltTypeQuals,
1425 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001426 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1427 "Size must be type- or value-dependent!");
1428
1429 // Since we don't unique expressions, it isn't possible to unique
1430 // dependently-sized array types.
1431
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001432 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001433 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1434 NumElts, ASM, EltTypeQuals,
1435 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001436
1437 DependentSizedArrayTypes.push_back(New);
1438 Types.push_back(New);
1439 return QualType(New, 0);
1440}
1441
Eli Friedmanc5773c42008-02-15 18:16:39 +00001442QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1443 ArrayType::ArraySizeModifier ASM,
1444 unsigned EltTypeQuals) {
1445 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001446 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001447
1448 void *InsertPos = 0;
1449 if (IncompleteArrayType *ATP =
1450 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1451 return QualType(ATP, 0);
1452
1453 // If the element type isn't canonical, this won't be a canonical type
1454 // either, so fill in the canonical type field.
1455 QualType Canonical;
1456
1457 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001458 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001459 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001460
1461 // Get the new insert position for the node we care about.
1462 IncompleteArrayType *NewIP =
1463 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001464 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001465 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001466
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001467 IncompleteArrayType *New
1468 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1469 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001470
1471 IncompleteArrayTypes.InsertNode(New, InsertPos);
1472 Types.push_back(New);
1473 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001474}
1475
Steve Naroff73322922007-07-18 18:00:27 +00001476/// getVectorType - Return the unique reference to a vector type of
1477/// the specified element type and size. VectorType must be a built-in type.
1478QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 BuiltinType *baseType;
1480
Chris Lattnerf52ab252008-04-06 22:59:24 +00001481 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001482 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001483
1484 // Check if we've already instantiated a vector of this type.
1485 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001486 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 void *InsertPos = 0;
1488 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(VTP, 0);
1490
1491 // If the element type isn't canonical, this won't be a canonical type either,
1492 // so fill in the canonical type field.
1493 QualType Canonical;
1494 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001495 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496
1497 // Get the new insert position for the node we care about.
1498 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001499 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 }
Steve Narofff83820b2009-01-27 22:08:43 +00001501 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 VectorTypes.InsertNode(New, InsertPos);
1503 Types.push_back(New);
1504 return QualType(New, 0);
1505}
1506
Nate Begeman213541a2008-04-18 23:10:10 +00001507/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001508/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001509QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001510 BuiltinType *baseType;
1511
Chris Lattnerf52ab252008-04-06 22:59:24 +00001512 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001513 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001514
1515 // Check if we've already instantiated a vector of this type.
1516 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001517 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001518 void *InsertPos = 0;
1519 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1520 return QualType(VTP, 0);
1521
1522 // If the element type isn't canonical, this won't be a canonical type either,
1523 // so fill in the canonical type field.
1524 QualType Canonical;
1525 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001526 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001527
1528 // Get the new insert position for the node we care about.
1529 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001530 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001531 }
Steve Narofff83820b2009-01-27 22:08:43 +00001532 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001533 VectorTypes.InsertNode(New, InsertPos);
1534 Types.push_back(New);
1535 return QualType(New, 0);
1536}
1537
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001538QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1539 Expr *SizeExpr,
1540 SourceLocation AttrLoc) {
1541 DependentSizedExtVectorType *New =
1542 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1543 SizeExpr, AttrLoc);
1544
1545 DependentSizedExtVectorTypes.push_back(New);
1546 Types.push_back(New);
1547 return QualType(New, 0);
1548}
1549
Douglas Gregor72564e72009-02-26 23:50:07 +00001550/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001551///
Douglas Gregor72564e72009-02-26 23:50:07 +00001552QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 // Unique functions, to guarantee there is only one function of a particular
1554 // structure.
1555 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001556 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557
1558 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001559 if (FunctionNoProtoType *FT =
1560 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 return QualType(FT, 0);
1562
1563 QualType Canonical;
1564 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001565 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001566
1567 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001568 FunctionNoProtoType *NewIP =
1569 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001570 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 }
1572
Douglas Gregor72564e72009-02-26 23:50:07 +00001573 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001575 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 return QualType(New, 0);
1577}
1578
1579/// getFunctionType - Return a normal function type with a typed argument
1580/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001581QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001582 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001583 unsigned TypeQuals, bool hasExceptionSpec,
1584 bool hasAnyExceptionSpec, unsigned NumExs,
1585 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // Unique functions, to guarantee there is only one function of a particular
1587 // structure.
1588 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001589 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001590 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1591 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592
1593 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001594 if (FunctionProtoType *FTP =
1595 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001597
1598 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001600 if (hasExceptionSpec)
1601 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1603 if (!ArgArray[i]->isCanonical())
1604 isCanonical = false;
1605
1606 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001607 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 QualType Canonical;
1609 if (!isCanonical) {
1610 llvm::SmallVector<QualType, 16> CanonicalArgs;
1611 CanonicalArgs.reserve(NumArgs);
1612 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001613 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001614
Chris Lattnerf52ab252008-04-06 22:59:24 +00001615 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001616 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001617 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001618
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001620 FunctionProtoType *NewIP =
1621 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001622 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001624
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001626 // for two variable size arrays (for parameter and exception types) at the
1627 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001628 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001629 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1630 NumArgs*sizeof(QualType) +
1631 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001632 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001633 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1634 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001636 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 return QualType(FTP, 0);
1638}
1639
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001640/// getTypeDeclType - Return the unique reference to the type for the
1641/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001642QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001643 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001644 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1645
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001646 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001647 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001648 else if (isa<TemplateTypeParmDecl>(Decl)) {
1649 assert(false && "Template type parameter types are always available.");
1650 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001651 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001652
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001653 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001654 if (PrevDecl)
1655 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001656 else
1657 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001658 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001659 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1660 if (PrevDecl)
1661 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001662 else
1663 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001664 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001665 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001666 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001667
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001668 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001669 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001670}
1671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672/// getTypedefType - Return the unique reference to the type for the
1673/// specified typename decl.
1674QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1675 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1676
Chris Lattnerf52ab252008-04-06 22:59:24 +00001677 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001678 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 Types.push_back(Decl->TypeForDecl);
1680 return QualType(Decl->TypeForDecl, 0);
1681}
1682
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001683/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001684/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001685QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001686 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1687
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001688 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1689 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001690 Types.push_back(Decl->TypeForDecl);
1691 return QualType(Decl->TypeForDecl, 0);
1692}
1693
Douglas Gregorfab9d672009-02-05 23:33:38 +00001694/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001695/// parameter or parameter pack with the given depth, index, and (optionally)
1696/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001697QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001698 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001699 IdentifierInfo *Name) {
1700 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001701 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001702 void *InsertPos = 0;
1703 TemplateTypeParmType *TypeParm
1704 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1705
1706 if (TypeParm)
1707 return QualType(TypeParm, 0);
1708
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001709 if (Name) {
1710 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1711 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1712 Name, Canon);
1713 } else
1714 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001715
1716 Types.push_back(TypeParm);
1717 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1718
1719 return QualType(TypeParm, 0);
1720}
1721
Douglas Gregor55f6b142009-02-09 18:46:07 +00001722QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001723ASTContext::getTemplateSpecializationType(TemplateName Template,
1724 const TemplateArgument *Args,
1725 unsigned NumArgs,
1726 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001727 if (!Canon.isNull())
1728 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001729
Douglas Gregor55f6b142009-02-09 18:46:07 +00001730 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001731 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001732
Douglas Gregor55f6b142009-02-09 18:46:07 +00001733 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001734 TemplateSpecializationType *Spec
1735 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001736
1737 if (Spec)
1738 return QualType(Spec, 0);
1739
Douglas Gregor7532dc62009-03-30 22:58:21 +00001740 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001741 sizeof(TemplateArgument) * NumArgs),
1742 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001743 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001744 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001745 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001746
1747 return QualType(Spec, 0);
1748}
1749
Douglas Gregore4e5b052009-03-19 00:18:19 +00001750QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001751ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001752 QualType NamedType) {
1753 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001754 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001755
1756 void *InsertPos = 0;
1757 QualifiedNameType *T
1758 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1759 if (T)
1760 return QualType(T, 0);
1761
Douglas Gregorab452ba2009-03-26 23:50:42 +00001762 T = new (*this) QualifiedNameType(NNS, NamedType,
1763 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001764 Types.push_back(T);
1765 QualifiedNameTypes.InsertNode(T, InsertPos);
1766 return QualType(T, 0);
1767}
1768
Douglas Gregord57959a2009-03-27 23:10:48 +00001769QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1770 const IdentifierInfo *Name,
1771 QualType Canon) {
1772 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1773
1774 if (Canon.isNull()) {
1775 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1776 if (CanonNNS != NNS)
1777 Canon = getTypenameType(CanonNNS, Name);
1778 }
1779
1780 llvm::FoldingSetNodeID ID;
1781 TypenameType::Profile(ID, NNS, Name);
1782
1783 void *InsertPos = 0;
1784 TypenameType *T
1785 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1786 if (T)
1787 return QualType(T, 0);
1788
1789 T = new (*this) TypenameType(NNS, Name, Canon);
1790 Types.push_back(T);
1791 TypenameTypes.InsertNode(T, InsertPos);
1792 return QualType(T, 0);
1793}
1794
Douglas Gregor17343172009-04-01 00:28:59 +00001795QualType
1796ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1797 const TemplateSpecializationType *TemplateId,
1798 QualType Canon) {
1799 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1800
1801 if (Canon.isNull()) {
1802 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1803 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1804 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1805 const TemplateSpecializationType *CanonTemplateId
1806 = CanonType->getAsTemplateSpecializationType();
1807 assert(CanonTemplateId &&
1808 "Canonical type must also be a template specialization type");
1809 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1810 }
1811 }
1812
1813 llvm::FoldingSetNodeID ID;
1814 TypenameType::Profile(ID, NNS, TemplateId);
1815
1816 void *InsertPos = 0;
1817 TypenameType *T
1818 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1819 if (T)
1820 return QualType(T, 0);
1821
1822 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1823 Types.push_back(T);
1824 TypenameTypes.InsertNode(T, InsertPos);
1825 return QualType(T, 0);
1826}
1827
Chris Lattner88cb27a2008-04-07 04:56:42 +00001828/// CmpProtocolNames - Comparison predicate for sorting protocols
1829/// alphabetically.
1830static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1831 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001832 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001833}
1834
1835static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1836 unsigned &NumProtocols) {
1837 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1838
1839 // Sort protocols, keyed by name.
1840 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1841
1842 // Remove duplicates.
1843 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1844 NumProtocols = ProtocolsEnd-Protocols;
1845}
1846
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001847/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1848/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001849QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001850 ObjCProtocolDecl **Protocols,
1851 unsigned NumProtocols) {
Steve Naroff14108da2009-07-10 23:34:53 +00001852 if (InterfaceT.isNull())
1853 InterfaceT = QualType(ObjCObjectPointerType::getIdInterface(), 0);
1854
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001855 // Sort the protocol list alphabetically to canonicalize it.
1856 if (NumProtocols)
1857 SortAndUniqueProtocols(Protocols, NumProtocols);
1858
1859 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001860 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001861
1862 void *InsertPos = 0;
1863 if (ObjCObjectPointerType *QT =
1864 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1865 return QualType(QT, 0);
1866
1867 // No Match;
1868 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001869 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001870
1871 Types.push_back(QType);
1872 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1873 return QualType(QType, 0);
1874}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001875
Chris Lattner065f0d72008-04-07 04:44:08 +00001876/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1877/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001878QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1879 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001880 // Sort the protocol list alphabetically to canonicalize it.
1881 SortAndUniqueProtocols(Protocols, NumProtocols);
1882
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001883 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001884 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001885
1886 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001887 if (ObjCQualifiedInterfaceType *QT =
1888 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001889 return QualType(QT, 0);
1890
1891 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001892 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001893 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001894
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001895 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001896 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001897 return QualType(QType, 0);
1898}
1899
Douglas Gregor72564e72009-02-26 23:50:07 +00001900/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1901/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001902/// multiple declarations that refer to "typeof(x)" all contain different
1903/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1904/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001905QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001906 TypeOfExprType *toe;
1907 if (tofExpr->isTypeDependent())
1908 toe = new (*this, 8) TypeOfExprType(tofExpr);
1909 else {
1910 QualType Canonical = getCanonicalType(tofExpr->getType());
1911 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1912 }
Steve Naroff9752f252007-08-01 18:02:17 +00001913 Types.push_back(toe);
1914 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001915}
1916
Steve Naroff9752f252007-08-01 18:02:17 +00001917/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1918/// TypeOfType AST's. The only motivation to unique these nodes would be
1919/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1920/// an issue. This doesn't effect the type checker, since it operates
1921/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001922QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001923 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001924 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001925 Types.push_back(tot);
1926 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001927}
1928
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001929/// getDecltypeForExpr - Given an expr, will return the decltype for that
1930/// expression, according to the rules in C++0x [dcl.type.simple]p4
1931static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001932 if (e->isTypeDependent())
1933 return Context.DependentTy;
1934
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001935 // If e is an id expression or a class member access, decltype(e) is defined
1936 // as the type of the entity named by e.
1937 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1938 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1939 return VD->getType();
1940 }
1941 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1942 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1943 return FD->getType();
1944 }
1945 // If e is a function call or an invocation of an overloaded operator,
1946 // (parentheses around e are ignored), decltype(e) is defined as the
1947 // return type of that function.
1948 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1949 return CE->getCallReturnType();
1950
1951 QualType T = e->getType();
1952
1953 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1954 // defined as T&, otherwise decltype(e) is defined as T.
1955 if (e->isLvalue(Context) == Expr::LV_Valid)
1956 T = Context.getLValueReferenceType(T);
1957
1958 return T;
1959}
1960
Anders Carlsson395b4752009-06-24 19:06:50 +00001961/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1962/// DecltypeType AST's. The only motivation to unique these nodes would be
1963/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1964/// an issue. This doesn't effect the type checker, since it operates
1965/// on canonical type's (which are always unique).
1966QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001967 DecltypeType *dt;
1968 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson563a03b2009-07-10 19:20:26 +00001969 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregordd0257c2009-07-08 00:03:05 +00001970 else {
1971 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00001972 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00001973 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001974 Types.push_back(dt);
1975 return QualType(dt, 0);
1976}
1977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978/// getTagDeclType - Return the unique reference to the type for the
1979/// specified TagDecl (struct/union/class/enum) decl.
1980QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001981 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001982 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001983}
1984
1985/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1986/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1987/// needs to agree with the definition in <stddef.h>.
1988QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001989 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001990}
1991
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001992/// getSignedWCharType - Return the type of "signed wchar_t".
1993/// Used when in C++, as a GCC extension.
1994QualType ASTContext::getSignedWCharType() const {
1995 // FIXME: derive from "Target" ?
1996 return WCharTy;
1997}
1998
1999/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2000/// Used when in C++, as a GCC extension.
2001QualType ASTContext::getUnsignedWCharType() const {
2002 // FIXME: derive from "Target" ?
2003 return UnsignedIntTy;
2004}
2005
Chris Lattner8b9023b2007-07-13 03:05:23 +00002006/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2007/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2008QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002009 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002010}
2011
Chris Lattnere6327742008-04-02 05:18:44 +00002012//===----------------------------------------------------------------------===//
2013// Type Operators
2014//===----------------------------------------------------------------------===//
2015
Chris Lattner77c96472008-04-06 22:41:35 +00002016/// getCanonicalType - Return the canonical (structural) type corresponding to
2017/// the specified potentially non-canonical type. The non-canonical version
2018/// of a type may have many "decorated" versions of types. Decorators can
2019/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2020/// to be free of any of these, allowing two canonical types to be compared
2021/// for exact equality with a simple pointer comparison.
2022QualType ASTContext::getCanonicalType(QualType T) {
2023 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002024
2025 // If the result has type qualifiers, make sure to canonicalize them as well.
2026 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2027 if (TypeQuals == 0) return CanType;
2028
2029 // If the type qualifiers are on an array type, get the canonical type of the
2030 // array with the qualifiers applied to the element type.
2031 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2032 if (!AT)
2033 return CanType.getQualifiedType(TypeQuals);
2034
2035 // Get the canonical version of the element with the extra qualifiers on it.
2036 // This can recursively sink qualifiers through multiple levels of arrays.
2037 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2038 NewEltTy = getCanonicalType(NewEltTy);
2039
2040 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2041 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2042 CAT->getIndexTypeQualifier());
2043 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2044 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2045 IAT->getIndexTypeQualifier());
2046
Douglas Gregor898574e2008-12-05 23:32:09 +00002047 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002048 return getDependentSizedArrayType(NewEltTy,
2049 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002050 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002051 DSAT->getIndexTypeQualifier(),
2052 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002053
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002054 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002055 return getVariableArrayType(NewEltTy,
2056 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002057 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002058 VAT->getIndexTypeQualifier(),
2059 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002060}
2061
Douglas Gregor7da97d02009-05-10 22:57:19 +00002062Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00002063 if (!D)
2064 return 0;
2065
Douglas Gregor7da97d02009-05-10 22:57:19 +00002066 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2067 QualType T = getTagDeclType(Tag);
2068 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2069 ->getDecl());
2070 }
2071
2072 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2073 while (Template->getPreviousDeclaration())
2074 Template = Template->getPreviousDeclaration();
2075 return Template;
2076 }
2077
2078 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2079 while (Function->getPreviousDeclaration())
2080 Function = Function->getPreviousDeclaration();
2081 return const_cast<FunctionDecl *>(Function);
2082 }
2083
Douglas Gregor127102b2009-06-29 20:59:39 +00002084 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2085 while (FunTmpl->getPreviousDeclaration())
2086 FunTmpl = FunTmpl->getPreviousDeclaration();
2087 return FunTmpl;
2088 }
2089
Douglas Gregor7da97d02009-05-10 22:57:19 +00002090 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2091 while (Var->getPreviousDeclaration())
2092 Var = Var->getPreviousDeclaration();
2093 return const_cast<VarDecl *>(Var);
2094 }
2095
2096 return D;
2097}
2098
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002099TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2100 // If this template name refers to a template, the canonical
2101 // template name merely stores the template itself.
2102 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002103 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002104
2105 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2106 assert(DTN && "Non-dependent template names must refer to template decls.");
2107 return DTN->CanonicalTemplateName;
2108}
2109
Douglas Gregord57959a2009-03-27 23:10:48 +00002110NestedNameSpecifier *
2111ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2112 if (!NNS)
2113 return 0;
2114
2115 switch (NNS->getKind()) {
2116 case NestedNameSpecifier::Identifier:
2117 // Canonicalize the prefix but keep the identifier the same.
2118 return NestedNameSpecifier::Create(*this,
2119 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2120 NNS->getAsIdentifier());
2121
2122 case NestedNameSpecifier::Namespace:
2123 // A namespace is canonical; build a nested-name-specifier with
2124 // this namespace and no prefix.
2125 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2126
2127 case NestedNameSpecifier::TypeSpec:
2128 case NestedNameSpecifier::TypeSpecWithTemplate: {
2129 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2130 NestedNameSpecifier *Prefix = 0;
2131
2132 // FIXME: This isn't the right check!
2133 if (T->isDependentType())
2134 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2135
2136 return NestedNameSpecifier::Create(*this, Prefix,
2137 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2138 T.getTypePtr());
2139 }
2140
2141 case NestedNameSpecifier::Global:
2142 // The global specifier is canonical and unique.
2143 return NNS;
2144 }
2145
2146 // Required to silence a GCC warning
2147 return 0;
2148}
2149
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002150
2151const ArrayType *ASTContext::getAsArrayType(QualType T) {
2152 // Handle the non-qualified case efficiently.
2153 if (T.getCVRQualifiers() == 0) {
2154 // Handle the common positive case fast.
2155 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2156 return AT;
2157 }
2158
2159 // Handle the common negative case fast, ignoring CVR qualifiers.
2160 QualType CType = T->getCanonicalTypeInternal();
2161
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002162 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002163 // test.
2164 if (!isa<ArrayType>(CType) &&
2165 !isa<ArrayType>(CType.getUnqualifiedType()))
2166 return 0;
2167
2168 // Apply any CVR qualifiers from the array type to the element type. This
2169 // implements C99 6.7.3p8: "If the specification of an array type includes
2170 // any type qualifiers, the element type is so qualified, not the array type."
2171
2172 // If we get here, we either have type qualifiers on the type, or we have
2173 // sugar such as a typedef in the way. If we have type qualifiers on the type
2174 // we must propagate them down into the elemeng type.
2175 unsigned CVRQuals = T.getCVRQualifiers();
2176 unsigned AddrSpace = 0;
2177 Type *Ty = T.getTypePtr();
2178
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002179 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002180 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002181 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2182 AddrSpace = EXTQT->getAddressSpace();
2183 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002184 } else {
2185 T = Ty->getDesugaredType();
2186 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2187 break;
2188 CVRQuals |= T.getCVRQualifiers();
2189 Ty = T.getTypePtr();
2190 }
2191 }
2192
2193 // If we have a simple case, just return now.
2194 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2195 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2196 return ATy;
2197
2198 // Otherwise, we have an array and we have qualifiers on it. Push the
2199 // qualifiers into the array element type and return a new array type.
2200 // Get the canonical version of the element with the extra qualifiers on it.
2201 // This can recursively sink qualifiers through multiple levels of arrays.
2202 QualType NewEltTy = ATy->getElementType();
2203 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002204 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002205 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2206
2207 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2208 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2209 CAT->getSizeModifier(),
2210 CAT->getIndexTypeQualifier()));
2211 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2212 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2213 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002214 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002215
Douglas Gregor898574e2008-12-05 23:32:09 +00002216 if (const DependentSizedArrayType *DSAT
2217 = dyn_cast<DependentSizedArrayType>(ATy))
2218 return cast<ArrayType>(
2219 getDependentSizedArrayType(NewEltTy,
2220 DSAT->getSizeExpr(),
2221 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002222 DSAT->getIndexTypeQualifier(),
2223 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002224
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002225 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002226 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2227 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002228 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002229 VAT->getIndexTypeQualifier(),
2230 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002231}
2232
2233
Chris Lattnere6327742008-04-02 05:18:44 +00002234/// getArrayDecayedType - Return the properly qualified result of decaying the
2235/// specified array type to a pointer. This operation is non-trivial when
2236/// handling typedefs etc. The canonical type of "T" must be an array type,
2237/// this returns a pointer to a properly qualified element of the array.
2238///
2239/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2240QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002241 // Get the element type with 'getAsArrayType' so that we don't lose any
2242 // typedefs in the element type of the array. This also handles propagation
2243 // of type qualifiers from the array type into the element type if present
2244 // (C99 6.7.3p8).
2245 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2246 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002247
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002248 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002249
2250 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002251 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002252}
2253
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002254QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002255 QualType ElemTy = VAT->getElementType();
2256
2257 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2258 return getBaseElementType(VAT);
2259
2260 return ElemTy;
2261}
2262
Reid Spencer5f016e22007-07-11 17:01:13 +00002263/// getFloatingRank - Return a relative rank for floating point types.
2264/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002265static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002266 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002268
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002269 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002270 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002271 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 case BuiltinType::Float: return FloatRank;
2273 case BuiltinType::Double: return DoubleRank;
2274 case BuiltinType::LongDouble: return LongDoubleRank;
2275 }
2276}
2277
Steve Naroff716c7302007-08-27 01:41:48 +00002278/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2279/// point or a complex type (based on typeDomain/typeSize).
2280/// 'typeDomain' is a real floating point or complex type.
2281/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002282QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2283 QualType Domain) const {
2284 FloatingRank EltRank = getFloatingRank(Size);
2285 if (Domain->isComplexType()) {
2286 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002287 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002288 case FloatRank: return FloatComplexTy;
2289 case DoubleRank: return DoubleComplexTy;
2290 case LongDoubleRank: return LongDoubleComplexTy;
2291 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 }
Chris Lattner1361b112008-04-06 23:58:54 +00002293
2294 assert(Domain->isRealFloatingType() && "Unknown domain!");
2295 switch (EltRank) {
2296 default: assert(0 && "getFloatingRank(): illegal value for rank");
2297 case FloatRank: return FloatTy;
2298 case DoubleRank: return DoubleTy;
2299 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002300 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002301}
2302
Chris Lattner7cfeb082008-04-06 23:55:33 +00002303/// getFloatingTypeOrder - Compare the rank of the two specified floating
2304/// point types, ignoring the domain of the type (i.e. 'double' ==
2305/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2306/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002307int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2308 FloatingRank LHSR = getFloatingRank(LHS);
2309 FloatingRank RHSR = getFloatingRank(RHS);
2310
2311 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002312 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002313 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002314 return 1;
2315 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002316}
2317
Chris Lattnerf52ab252008-04-06 22:59:24 +00002318/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2319/// routine will assert if passed a built-in type that isn't an integer or enum,
2320/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002321unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002322 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002323 if (EnumType* ET = dyn_cast<EnumType>(T))
2324 T = ET->getDecl()->getIntegerType().getTypePtr();
2325
Eli Friedmana3426752009-07-05 23:44:27 +00002326 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2327 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2328
Eli Friedmanf98aba32009-02-13 02:31:07 +00002329 // There are two things which impact the integer rank: the width, and
2330 // the ordering of builtins. The builtin ordering is encoded in the
2331 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002332 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002333 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002334
Chris Lattnerf52ab252008-04-06 22:59:24 +00002335 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002336 default: assert(0 && "getIntegerRank(): not a built-in integer");
2337 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002338 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002339 case BuiltinType::Char_S:
2340 case BuiltinType::Char_U:
2341 case BuiltinType::SChar:
2342 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002343 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002344 case BuiltinType::Short:
2345 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002346 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002347 case BuiltinType::Int:
2348 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002349 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002350 case BuiltinType::Long:
2351 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002352 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002353 case BuiltinType::LongLong:
2354 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002355 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002356 case BuiltinType::Int128:
2357 case BuiltinType::UInt128:
2358 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002359 }
2360}
2361
Chris Lattner7cfeb082008-04-06 23:55:33 +00002362/// getIntegerTypeOrder - Returns the highest ranked integer type:
2363/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2364/// LHS < RHS, return -1.
2365int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002366 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2367 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002368 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002369
Chris Lattnerf52ab252008-04-06 22:59:24 +00002370 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2371 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002372
Chris Lattner7cfeb082008-04-06 23:55:33 +00002373 unsigned LHSRank = getIntegerRank(LHSC);
2374 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002375
Chris Lattner7cfeb082008-04-06 23:55:33 +00002376 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2377 if (LHSRank == RHSRank) return 0;
2378 return LHSRank > RHSRank ? 1 : -1;
2379 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002380
Chris Lattner7cfeb082008-04-06 23:55:33 +00002381 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2382 if (LHSUnsigned) {
2383 // If the unsigned [LHS] type is larger, return it.
2384 if (LHSRank >= RHSRank)
2385 return 1;
2386
2387 // If the signed type can represent all values of the unsigned type, it
2388 // wins. Because we are dealing with 2's complement and types that are
2389 // powers of two larger than each other, this is always safe.
2390 return -1;
2391 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002392
Chris Lattner7cfeb082008-04-06 23:55:33 +00002393 // If the unsigned [RHS] type is larger, return it.
2394 if (RHSRank >= LHSRank)
2395 return -1;
2396
2397 // If the signed type can represent all values of the unsigned type, it
2398 // wins. Because we are dealing with 2's complement and types that are
2399 // powers of two larger than each other, this is always safe.
2400 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002401}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002402
2403// getCFConstantStringType - Return the type used for constant CFStrings.
2404QualType ASTContext::getCFConstantStringType() {
2405 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002406 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002407 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002408 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002409 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002410
2411 // const int *isa;
2412 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002413 // int flags;
2414 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002415 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002416 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002417 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002418 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002419
Anders Carlsson71993dd2007-08-17 05:31:46 +00002420 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002421 for (unsigned i = 0; i < 4; ++i) {
2422 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2423 SourceLocation(), 0,
2424 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002425 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002426 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002427 }
2428
2429 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002430 }
2431
2432 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002433}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002434
Douglas Gregor319ac892009-04-23 22:29:11 +00002435void ASTContext::setCFConstantStringType(QualType T) {
2436 const RecordType *Rec = T->getAsRecordType();
2437 assert(Rec && "Invalid CFConstantStringType");
2438 CFConstantStringTypeDecl = Rec->getDecl();
2439}
2440
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002441QualType ASTContext::getObjCFastEnumerationStateType()
2442{
2443 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002444 ObjCFastEnumerationStateTypeDecl =
2445 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2446 &Idents.get("__objcFastEnumerationState"));
2447
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002448 QualType FieldTypes[] = {
2449 UnsignedLongTy,
2450 getPointerType(ObjCIdType),
2451 getPointerType(UnsignedLongTy),
2452 getConstantArrayType(UnsignedLongTy,
2453 llvm::APInt(32, 5), ArrayType::Normal, 0)
2454 };
2455
Douglas Gregor44b43212008-12-11 16:49:14 +00002456 for (size_t i = 0; i < 4; ++i) {
2457 FieldDecl *Field = FieldDecl::Create(*this,
2458 ObjCFastEnumerationStateTypeDecl,
2459 SourceLocation(), 0,
2460 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002461 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002462 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002463 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002464
Douglas Gregor44b43212008-12-11 16:49:14 +00002465 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002466 }
2467
2468 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2469}
2470
Douglas Gregor319ac892009-04-23 22:29:11 +00002471void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2472 const RecordType *Rec = T->getAsRecordType();
2473 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2474 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2475}
2476
Anders Carlssone8c49532007-10-29 06:33:42 +00002477// This returns true if a type has been typedefed to BOOL:
2478// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002479static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002480 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002481 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2482 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002483
2484 return false;
2485}
2486
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002487/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002488/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002489int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002490 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002491
2492 // Make all integer and enum types at least as large as an int
2493 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002494 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002495 // Treat arrays as pointers, since that's how they're passed in.
2496 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002497 sz = getTypeSize(VoidPtrTy);
2498 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002499}
2500
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002501/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002502/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002503void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002504 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002505 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002506 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002507 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002508 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002509 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002510 // Compute size of all parameters.
2511 // Start with computing size of a pointer in number of bytes.
2512 // FIXME: There might(should) be a better way of doing this computation!
2513 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002514 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002515 // The first two arguments (self and _cmd) are pointers; account for
2516 // their size.
2517 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002518 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2519 E = Decl->param_end(); PI != E; ++PI) {
2520 QualType PType = (*PI)->getType();
2521 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002522 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002523 ParmOffset += sz;
2524 }
2525 S += llvm::utostr(ParmOffset);
2526 S += "@0:";
2527 S += llvm::utostr(PtrSize);
2528
2529 // Argument types.
2530 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002531 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2532 E = Decl->param_end(); PI != E; ++PI) {
2533 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002534 QualType PType = PVDecl->getOriginalType();
2535 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002536 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2537 // Use array's original type only if it has known number of
2538 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002539 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002540 PType = PVDecl->getType();
2541 } else if (PType->isFunctionType())
2542 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002543 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002544 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002545 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002546 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002547 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002548 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002549 }
2550}
2551
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002552/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002553/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002554/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2555/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002556/// Property attributes are stored as a comma-delimited C string. The simple
2557/// attributes readonly and bycopy are encoded as single characters. The
2558/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2559/// encoded as single characters, followed by an identifier. Property types
2560/// are also encoded as a parametrized attribute. The characters used to encode
2561/// these attributes are defined by the following enumeration:
2562/// @code
2563/// enum PropertyAttributes {
2564/// kPropertyReadOnly = 'R', // property is read-only.
2565/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2566/// kPropertyByref = '&', // property is a reference to the value last assigned
2567/// kPropertyDynamic = 'D', // property is dynamic
2568/// kPropertyGetter = 'G', // followed by getter selector name
2569/// kPropertySetter = 'S', // followed by setter selector name
2570/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2571/// kPropertyType = 't' // followed by old-style type encoding.
2572/// kPropertyWeak = 'W' // 'weak' property
2573/// kPropertyStrong = 'P' // property GC'able
2574/// kPropertyNonAtomic = 'N' // property non-atomic
2575/// };
2576/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002577void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2578 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002579 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002580 // Collect information from the property implementation decl(s).
2581 bool Dynamic = false;
2582 ObjCPropertyImplDecl *SynthesizePID = 0;
2583
2584 // FIXME: Duplicated code due to poor abstraction.
2585 if (Container) {
2586 if (const ObjCCategoryImplDecl *CID =
2587 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2588 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002589 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002590 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002591 ObjCPropertyImplDecl *PID = *i;
2592 if (PID->getPropertyDecl() == PD) {
2593 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2594 Dynamic = true;
2595 } else {
2596 SynthesizePID = PID;
2597 }
2598 }
2599 }
2600 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002601 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002602 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002603 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002604 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002605 ObjCPropertyImplDecl *PID = *i;
2606 if (PID->getPropertyDecl() == PD) {
2607 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2608 Dynamic = true;
2609 } else {
2610 SynthesizePID = PID;
2611 }
2612 }
2613 }
2614 }
2615 }
2616
2617 // FIXME: This is not very efficient.
2618 S = "T";
2619
2620 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002621 // GCC has some special rules regarding encoding of properties which
2622 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002623 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002624 true /* outermost type */,
2625 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002626
2627 if (PD->isReadOnly()) {
2628 S += ",R";
2629 } else {
2630 switch (PD->getSetterKind()) {
2631 case ObjCPropertyDecl::Assign: break;
2632 case ObjCPropertyDecl::Copy: S += ",C"; break;
2633 case ObjCPropertyDecl::Retain: S += ",&"; break;
2634 }
2635 }
2636
2637 // It really isn't clear at all what this means, since properties
2638 // are "dynamic by default".
2639 if (Dynamic)
2640 S += ",D";
2641
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002642 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2643 S += ",N";
2644
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002645 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2646 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002647 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002648 }
2649
2650 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2651 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002652 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002653 }
2654
2655 if (SynthesizePID) {
2656 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2657 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002658 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002659 }
2660
2661 // FIXME: OBJCGC: weak & strong
2662}
2663
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002664/// getLegacyIntegralTypeEncoding -
2665/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002666/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002667/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2668///
2669void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2670 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2671 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002672 if (BT->getKind() == BuiltinType::ULong &&
2673 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002674 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002675 else
2676 if (BT->getKind() == BuiltinType::Long &&
2677 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002678 PointeeTy = IntTy;
2679 }
2680 }
2681}
2682
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002683void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002684 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002685 // We follow the behavior of gcc, expanding structures which are
2686 // directly pointed to, and expanding embedded structures. Note that
2687 // these rules are sufficient to prevent recursive encoding of the
2688 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002689 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2690 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002691}
2692
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002693static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002694 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002695 const Expr *E = FD->getBitWidth();
2696 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2697 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002698 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002699 S += 'b';
2700 S += llvm::utostr(N);
2701}
2702
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002703void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2704 bool ExpandPointedToStructures,
2705 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002706 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002707 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002708 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002709 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002710 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002711 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002712 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002713 else {
2714 char encoding;
2715 switch (BT->getKind()) {
2716 default: assert(0 && "Unhandled builtin type kind");
2717 case BuiltinType::Void: encoding = 'v'; break;
2718 case BuiltinType::Bool: encoding = 'B'; break;
2719 case BuiltinType::Char_U:
2720 case BuiltinType::UChar: encoding = 'C'; break;
2721 case BuiltinType::UShort: encoding = 'S'; break;
2722 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002723 case BuiltinType::ULong:
2724 encoding =
2725 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2726 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002727 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002728 case BuiltinType::ULongLong: encoding = 'Q'; break;
2729 case BuiltinType::Char_S:
2730 case BuiltinType::SChar: encoding = 'c'; break;
2731 case BuiltinType::Short: encoding = 's'; break;
2732 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002733 case BuiltinType::Long:
2734 encoding =
2735 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2736 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002737 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002738 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002739 case BuiltinType::Float: encoding = 'f'; break;
2740 case BuiltinType::Double: encoding = 'd'; break;
2741 case BuiltinType::LongDouble: encoding = 'd'; break;
2742 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002743
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002744 S += encoding;
2745 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002746 } else if (const ComplexType *CT = T->getAsComplexType()) {
2747 S += 'j';
2748 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2749 false);
Steve Naroff14108da2009-07-10 23:34:53 +00002750 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002751 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002752 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002753 bool isReadOnly = false;
2754 // For historical/compatibility reasons, the read-only qualifier of the
2755 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2756 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2757 // Also, do not emit the 'r' for anything but the outermost type!
2758 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2759 if (OutermostType && T.isConstQualified()) {
2760 isReadOnly = true;
2761 S += 'r';
2762 }
2763 }
2764 else if (OutermostType) {
2765 QualType P = PointeeTy;
2766 while (P->getAsPointerType())
2767 P = P->getAsPointerType()->getPointeeType();
2768 if (P.isConstQualified()) {
2769 isReadOnly = true;
2770 S += 'r';
2771 }
2772 }
2773 if (isReadOnly) {
2774 // Another legacy compatibility encoding. Some ObjC qualifier and type
2775 // combinations need to be rearranged.
2776 // Rewrite "in const" from "nr" to "rn"
2777 const char * s = S.c_str();
2778 int len = S.length();
2779 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2780 std::string replace = "rn";
2781 S.replace(S.end()-2, S.end(), replace);
2782 }
2783 }
Steve Naroff14108da2009-07-10 23:34:53 +00002784 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002785 S += ':';
2786 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002787 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002788
2789 if (PointeeTy->isCharType()) {
2790 // char pointer types should be encoded as '*' unless it is a
2791 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002792 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002793 S += '*';
2794 return;
2795 }
2796 }
2797
2798 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002799 getLegacyIntegralTypeEncoding(PointeeTy);
2800
2801 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002802 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002803 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002804 } else if (const ArrayType *AT =
2805 // Ignore type qualifiers etc.
2806 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002807 if (isa<IncompleteArrayType>(AT)) {
2808 // Incomplete arrays are encoded as a pointer to the array element.
2809 S += '^';
2810
2811 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2812 false, ExpandStructures, FD);
2813 } else {
2814 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002815
Anders Carlsson559a8332009-02-22 01:38:57 +00002816 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2817 S += llvm::utostr(CAT->getSize().getZExtValue());
2818 else {
2819 //Variable length arrays are encoded as a regular array with 0 elements.
2820 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2821 S += '0';
2822 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002823
Anders Carlsson559a8332009-02-22 01:38:57 +00002824 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2825 false, ExpandStructures, FD);
2826 S += ']';
2827 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002828 } else if (T->getAsFunctionType()) {
2829 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002830 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002831 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002832 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002833 // Anonymous structures print as '?'
2834 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2835 S += II->getName();
2836 } else {
2837 S += '?';
2838 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002839 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002840 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002841 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2842 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002843 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002844 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002845 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002846 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002847 S += '"';
2848 }
2849
2850 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002851 if (Field->isBitField()) {
2852 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2853 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002854 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002855 QualType qt = Field->getType();
2856 getLegacyIntegralTypeEncoding(qt);
2857 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002858 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002859 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002860 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002861 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002862 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002863 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002864 if (FD && FD->isBitField())
2865 EncodeBitField(this, S, FD);
2866 else
2867 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002868 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002869 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002870 } else if (T->isObjCInterfaceType()) {
2871 // @encode(class_name)
2872 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2873 S += '{';
2874 const IdentifierInfo *II = OI->getIdentifier();
2875 S += II->getName();
2876 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002877 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002878 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002879 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002880 if (RecFields[i]->isBitField())
2881 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2882 RecFields[i]);
2883 else
2884 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2885 FD);
2886 }
2887 S += '}';
2888 }
Steve Naroff14108da2009-07-10 23:34:53 +00002889 else if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
2890 if (OPT->isObjCIdType()) {
2891 S += '@';
2892 return;
2893 } else if (OPT->isObjCClassType()) {
2894 S += '#';
2895 return;
2896 } else if (OPT->isObjCQualifiedIdType()) {
2897 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2898 ExpandPointedToStructures,
2899 ExpandStructures, FD);
2900 if (FD || EncodingProperty) {
2901 // Note that we do extended encoding of protocol qualifer list
2902 // Only when doing ivar or property encoding.
2903 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2904 S += '"';
2905 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2906 E = QIDT->qual_end(); I != E; ++I) {
2907 S += '<';
2908 S += (*I)->getNameAsString();
2909 S += '>';
2910 }
2911 S += '"';
2912 }
2913 return;
2914 } else {
2915 QualType PointeeTy = OPT->getPointeeType();
2916 if (!EncodingProperty &&
2917 isa<TypedefType>(PointeeTy.getTypePtr())) {
2918 // Another historical/compatibility reason.
2919 // We encode the underlying type which comes out as
2920 // {...};
2921 S += '^';
2922 getObjCEncodingForTypeImpl(PointeeTy, S,
2923 false, ExpandPointedToStructures,
2924 NULL);
2925 return;
2926 }
2927 S += '@';
2928 if (FD || EncodingProperty) {
2929 const ObjCInterfaceType *OIT = OPT->getInterfaceType();
2930 ObjCInterfaceDecl *OI = OIT->getDecl();
2931 S += '"';
2932 S += OI->getNameAsCString();
2933 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2934 E = OIT->qual_end(); I != E; ++I) {
2935 S += '<';
2936 S += (*I)->getNameAsString();
2937 S += '>';
2938 }
2939 S += '"';
2940 }
2941 return;
2942 }
2943 } else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002944 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002945}
2946
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002947void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002948 std::string& S) const {
2949 if (QT & Decl::OBJC_TQ_In)
2950 S += 'n';
2951 if (QT & Decl::OBJC_TQ_Inout)
2952 S += 'N';
2953 if (QT & Decl::OBJC_TQ_Out)
2954 S += 'o';
2955 if (QT & Decl::OBJC_TQ_Bycopy)
2956 S += 'O';
2957 if (QT & Decl::OBJC_TQ_Byref)
2958 S += 'R';
2959 if (QT & Decl::OBJC_TQ_Oneway)
2960 S += 'V';
2961}
2962
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002963void ASTContext::setBuiltinVaListType(QualType T)
2964{
2965 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2966
2967 BuiltinVaListType = T;
2968}
2969
Douglas Gregor319ac892009-04-23 22:29:11 +00002970void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002971{
Douglas Gregor319ac892009-04-23 22:29:11 +00002972 ObjCIdType = T;
Douglas Gregor319ac892009-04-23 22:29:11 +00002973 const TypedefType *TT = T->getAsTypedefType();
Steve Naroff14108da2009-07-10 23:34:53 +00002974 assert(TT && "missing 'id' typedef");
2975 const ObjCObjectPointerType *OPT =
2976 TT->getDecl()->getUnderlyingType()->getAsObjCObjectPointerType();
2977 assert(OPT && "missing 'id' type");
2978 ObjCObjectPointerType::setIdInterface(OPT->getPointeeType());
Steve Naroff7e219e42007-10-15 14:41:52 +00002979}
2980
Douglas Gregor319ac892009-04-23 22:29:11 +00002981void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002982{
Douglas Gregor319ac892009-04-23 22:29:11 +00002983 ObjCSelType = T;
2984
2985 const TypedefType *TT = T->getAsTypedefType();
2986 if (!TT)
2987 return;
2988 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002989
2990 // typedef struct objc_selector *SEL;
2991 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002992 if (!ptr)
2993 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002994 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002995 if (!rec)
2996 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002997 SelStructType = rec;
2998}
2999
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003001{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003002 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003003}
3004
Douglas Gregor319ac892009-04-23 22:29:11 +00003005void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00003006{
Douglas Gregor319ac892009-04-23 22:29:11 +00003007 ObjCClassType = T;
Douglas Gregor319ac892009-04-23 22:29:11 +00003008 const TypedefType *TT = T->getAsTypedefType();
Steve Naroff14108da2009-07-10 23:34:53 +00003009 assert(TT && "missing 'Class' typedef");
3010 const ObjCObjectPointerType *OPT =
3011 TT->getDecl()->getUnderlyingType()->getAsObjCObjectPointerType();
3012 assert(OPT && "missing 'Class' type");
3013 ObjCObjectPointerType::setClassInterface(OPT->getPointeeType());
Anders Carlsson8baaca52007-10-31 02:53:19 +00003014}
3015
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003016void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3017 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003018 "'NSConstantString' type already set!");
3019
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003020 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003021}
3022
Douglas Gregor7532dc62009-03-30 22:58:21 +00003023/// \brief Retrieve the template name that represents a qualified
3024/// template name such as \c std::vector.
3025TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3026 bool TemplateKeyword,
3027 TemplateDecl *Template) {
3028 llvm::FoldingSetNodeID ID;
3029 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3030
3031 void *InsertPos = 0;
3032 QualifiedTemplateName *QTN =
3033 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3034 if (!QTN) {
3035 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3036 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3037 }
3038
3039 return TemplateName(QTN);
3040}
3041
3042/// \brief Retrieve the template name that represents a dependent
3043/// template name such as \c MetaFun::template apply.
3044TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3045 const IdentifierInfo *Name) {
3046 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3047
3048 llvm::FoldingSetNodeID ID;
3049 DependentTemplateName::Profile(ID, NNS, Name);
3050
3051 void *InsertPos = 0;
3052 DependentTemplateName *QTN =
3053 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3054
3055 if (QTN)
3056 return TemplateName(QTN);
3057
3058 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3059 if (CanonNNS == NNS) {
3060 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3061 } else {
3062 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3063 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3064 }
3065
3066 DependentTemplateNames.InsertNode(QTN, InsertPos);
3067 return TemplateName(QTN);
3068}
3069
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003070/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003071/// TargetInfo, produce the corresponding type. The unsigned @p Type
3072/// is actually a value of type @c TargetInfo::IntType.
3073QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003074 switch (Type) {
3075 case TargetInfo::NoInt: return QualType();
3076 case TargetInfo::SignedShort: return ShortTy;
3077 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3078 case TargetInfo::SignedInt: return IntTy;
3079 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3080 case TargetInfo::SignedLong: return LongTy;
3081 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3082 case TargetInfo::SignedLongLong: return LongLongTy;
3083 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3084 }
3085
3086 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003087 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003088}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003089
3090//===----------------------------------------------------------------------===//
3091// Type Predicates.
3092//===----------------------------------------------------------------------===//
3093
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003094/// isObjCNSObjectType - Return true if this is an NSObject object using
3095/// NSObject attribute on a c-style pointer type.
3096/// FIXME - Make it work directly on types.
3097///
3098bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3099 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3100 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003101 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003102 return true;
3103 }
3104 return false;
3105}
3106
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003107/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3108/// to an object type. This includes "id" and "Class" (two 'special' pointers
3109/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3110/// ID type).
3111bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroff14108da2009-07-10 23:34:53 +00003112 if (Ty->isObjCObjectPointerType())
3113 return true;
Steve Naroffd4617772009-02-23 18:36:16 +00003114 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003115 return true;
3116
Steve Naroff6ae98502008-10-21 18:24:04 +00003117 // Blocks are objects.
3118 if (Ty->isBlockPointerType())
3119 return true;
3120
3121 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00003122 const PointerType *PT = Ty->getAsPointerType();
3123 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003124 return false;
3125
Chris Lattner16ede0e2009-04-12 23:51:02 +00003126 // If this a pointer to an interface (e.g. NSString*), it is ok.
3127 if (PT->getPointeeType()->isObjCInterfaceType() ||
3128 // If is has NSObject attribute, OK as well.
3129 isObjCNSObjectType(Ty))
3130 return true;
3131
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003132 // Check to see if this is 'id' or 'Class', both of which are typedefs for
3133 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00003134 // underlying type. Iteratively strip off typedefs so that we can handle
3135 // typedefs of typedefs.
3136 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3137 if (Ty.getUnqualifiedType() == getObjCIdType() ||
3138 Ty.getUnqualifiedType() == getObjCClassType())
3139 return true;
3140
3141 Ty = TDT->getDecl()->getUnderlyingType();
3142 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003143
Chris Lattner16ede0e2009-04-12 23:51:02 +00003144 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003145}
3146
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003147/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3148/// garbage collection attribute.
3149///
3150QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003151 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003152 if (getLangOptions().ObjC1 &&
3153 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003154 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003155 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003156 // (or pointers to them) be treated as though they were declared
3157 // as __strong.
3158 if (GCAttrs == QualType::GCNone) {
3159 if (isObjCObjectPointerType(Ty))
3160 GCAttrs = QualType::Strong;
3161 else if (Ty->isPointerType())
3162 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3163 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003164 // Non-pointers have none gc'able attribute regardless of the attribute
3165 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003166 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003167 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003168 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003169 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003170}
3171
Chris Lattner6ac46a42008-04-07 06:51:04 +00003172//===----------------------------------------------------------------------===//
3173// Type Compatibility Testing
3174//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003175
Chris Lattner6ac46a42008-04-07 06:51:04 +00003176/// areCompatVectorTypes - Return true if the two specified vector types are
3177/// compatible.
3178static bool areCompatVectorTypes(const VectorType *LHS,
3179 const VectorType *RHS) {
3180 assert(LHS->isCanonical() && RHS->isCanonical());
3181 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003182 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003183}
3184
Eli Friedman3d815e72008-08-22 00:56:42 +00003185/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003186/// compatible for assignment from RHS to LHS. This handles validation of any
3187/// protocol qualifiers on the LHS or RHS.
3188///
Steve Naroff14108da2009-07-10 23:34:53 +00003189/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3190bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3191 const ObjCObjectPointerType *RHSOPT) {
3192 // If either interface represents the built-in 'id' or 'Class' types,
3193 // then return true (no need to call canAssignObjCInterfaces()).
3194 if (LHSOPT->isObjCIdType() || RHSOPT->isObjCIdType() ||
3195 LHSOPT->isObjCClassType() || RHSOPT->isObjCClassType())
3196 return true;
3197
3198 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3199 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3200 if (!LHS || !RHS)
3201 return false;
3202 return canAssignObjCInterfaces(LHS, RHS);
3203}
3204
Eli Friedman3d815e72008-08-22 00:56:42 +00003205bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3206 const ObjCInterfaceType *RHS) {
Steve Naroff14108da2009-07-10 23:34:53 +00003207 // If either interface represents the built-in 'id' or 'Class' types,
3208 // then return true.
3209 if (LHS->isObjCIdInterface() || RHS->isObjCIdInterface() ||
3210 LHS->isObjCClassInterface() || RHS->isObjCClassInterface())
3211 return true;
3212
Chris Lattner6ac46a42008-04-07 06:51:04 +00003213 // Verify that the base decls are compatible: the RHS must be a subclass of
3214 // the LHS.
3215 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3216 return false;
3217
3218 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3219 // protocol qualified at all, then we are good.
3220 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3221 return true;
3222
3223 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3224 // isn't a superset.
3225 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3226 return true; // FIXME: should return false!
3227
3228 // Finally, we must have two protocol-qualified interfaces.
3229 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3230 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003231
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003232 // All LHS protocols must have a presence on the RHS.
3233 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003234
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003235 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3236 LHSPE = LHSP->qual_end();
3237 LHSPI != LHSPE; LHSPI++) {
3238 bool RHSImplementsProtocol = false;
3239
3240 // If the RHS doesn't implement the protocol on the left, the types
3241 // are incompatible.
3242 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3243 RHSPE = RHSP->qual_end();
3244 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3245 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3246 RHSImplementsProtocol = true;
3247 }
3248 // FIXME: For better diagnostics, consider passing back the protocol name.
3249 if (!RHSImplementsProtocol)
3250 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003251 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003252 // The RHS implements all protocols listed on the LHS.
3253 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003254}
3255
Steve Naroff389bf462009-02-12 17:52:19 +00003256bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3257 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003258 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3259 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003260
Steve Naroff14108da2009-07-10 23:34:53 +00003261 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003262 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003263
3264 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3265 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003266}
3267
Steve Naroffec0550f2007-10-15 20:41:53 +00003268/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3269/// both shall have the identically qualified version of a compatible type.
3270/// C99 6.2.7p1: Two types have compatible types if their types are the
3271/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003272bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3273 return !mergeTypes(LHS, RHS).isNull();
3274}
3275
3276QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3277 const FunctionType *lbase = lhs->getAsFunctionType();
3278 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003279 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3280 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003281 bool allLTypes = true;
3282 bool allRTypes = true;
3283
3284 // Check return type
3285 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3286 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003287 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3288 allLTypes = false;
3289 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3290 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003291
3292 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003293 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3294 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003295 unsigned lproto_nargs = lproto->getNumArgs();
3296 unsigned rproto_nargs = rproto->getNumArgs();
3297
3298 // Compatible functions must have the same number of arguments
3299 if (lproto_nargs != rproto_nargs)
3300 return QualType();
3301
3302 // Variadic and non-variadic functions aren't compatible
3303 if (lproto->isVariadic() != rproto->isVariadic())
3304 return QualType();
3305
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003306 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3307 return QualType();
3308
Eli Friedman3d815e72008-08-22 00:56:42 +00003309 // Check argument compatibility
3310 llvm::SmallVector<QualType, 10> types;
3311 for (unsigned i = 0; i < lproto_nargs; i++) {
3312 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3313 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3314 QualType argtype = mergeTypes(largtype, rargtype);
3315 if (argtype.isNull()) return QualType();
3316 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003317 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3318 allLTypes = false;
3319 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3320 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003321 }
3322 if (allLTypes) return lhs;
3323 if (allRTypes) return rhs;
3324 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003325 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003326 }
3327
3328 if (lproto) allRTypes = false;
3329 if (rproto) allLTypes = false;
3330
Douglas Gregor72564e72009-02-26 23:50:07 +00003331 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003332 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003333 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003334 if (proto->isVariadic()) return QualType();
3335 // Check that the types are compatible with the types that
3336 // would result from default argument promotions (C99 6.7.5.3p15).
3337 // The only types actually affected are promotable integer
3338 // types and floats, which would be passed as a different
3339 // type depending on whether the prototype is visible.
3340 unsigned proto_nargs = proto->getNumArgs();
3341 for (unsigned i = 0; i < proto_nargs; ++i) {
3342 QualType argTy = proto->getArgType(i);
3343 if (argTy->isPromotableIntegerType() ||
3344 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3345 return QualType();
3346 }
3347
3348 if (allLTypes) return lhs;
3349 if (allRTypes) return rhs;
3350 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003351 proto->getNumArgs(), lproto->isVariadic(),
3352 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003353 }
3354
3355 if (allLTypes) return lhs;
3356 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003357 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003358}
3359
3360QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003361 // C++ [expr]: If an expression initially has the type "reference to T", the
3362 // type is adjusted to "T" prior to any further analysis, the expression
3363 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003364 // expression is an lvalue unless the reference is an rvalue reference and
3365 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003366 // FIXME: C++ shouldn't be going through here! The rules are different
3367 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003368 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3369 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003370 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003371 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003372 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003373 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003374
Eli Friedman3d815e72008-08-22 00:56:42 +00003375 QualType LHSCan = getCanonicalType(LHS),
3376 RHSCan = getCanonicalType(RHS);
3377
3378 // If two types are identical, they are compatible.
3379 if (LHSCan == RHSCan)
3380 return LHS;
3381
3382 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003383 // Note that we handle extended qualifiers later, in the
3384 // case for ExtQualType.
3385 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003386 return QualType();
3387
Eli Friedman852d63b2009-06-01 01:22:52 +00003388 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3389 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003390
Chris Lattner1adb8832008-01-14 05:45:46 +00003391 // We want to consider the two function types to be the same for these
3392 // comparisons, just force one to the other.
3393 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3394 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003395
Eli Friedman07d25872009-06-02 05:28:56 +00003396 // Strip off objc_gc attributes off the top level so they can be merged.
3397 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003398 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003399 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3400 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003401 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003402 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003403 // __strong attribue is redundant if other decl is an objective-c
3404 // object pointer (or decorated with __strong attribute); otherwise
3405 // issue error.
3406 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3407 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003408 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003409 return QualType();
3410
Eli Friedman07d25872009-06-02 05:28:56 +00003411 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3412 RHS.getCVRQualifiers());
3413 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003414 if (!Result.isNull()) {
3415 if (Result.getObjCGCAttr() == QualType::GCNone)
3416 Result = getObjCGCQualType(Result, GCAttr);
3417 else if (Result.getObjCGCAttr() != GCAttr)
3418 Result = QualType();
3419 }
Eli Friedman07d25872009-06-02 05:28:56 +00003420 return Result;
3421 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003422 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003423 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003424 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3425 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003426 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3427 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003428 // __strong attribue is redundant if other decl is an objective-c
3429 // object pointer (or decorated with __strong attribute); otherwise
3430 // issue error.
3431 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3432 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003433 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003434 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003435
Eli Friedman07d25872009-06-02 05:28:56 +00003436 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3437 LHS.getCVRQualifiers());
3438 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003439 if (!Result.isNull()) {
3440 if (Result.getObjCGCAttr() == QualType::GCNone)
3441 Result = getObjCGCQualType(Result, GCAttr);
3442 else if (Result.getObjCGCAttr() != GCAttr)
3443 Result = QualType();
3444 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003445 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003446 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003447 }
3448
Eli Friedman4c721d32008-02-12 08:23:06 +00003449 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003450 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3451 LHSClass = Type::ConstantArray;
3452 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3453 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003454
Nate Begeman213541a2008-04-18 23:10:10 +00003455 // Canonicalize ExtVector -> Vector.
3456 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3457 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003458
Chris Lattnerb0489812008-04-07 06:38:24 +00003459 // Consider qualified interfaces and interfaces the same.
Steve Naroff14108da2009-07-10 23:34:53 +00003460 // FIXME: Remove (ObjCObjectPointerType should obsolete this funny business).
Chris Lattnerb0489812008-04-07 06:38:24 +00003461 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3462 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003463
Chris Lattnera36a61f2008-04-07 05:43:21 +00003464 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003465 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003466 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3467 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003468 if (const EnumType* ETy = LHS->getAsEnumType()) {
3469 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3470 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003471 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003472 if (const EnumType* ETy = RHS->getAsEnumType()) {
3473 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3474 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003475 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003476
Eli Friedman3d815e72008-08-22 00:56:42 +00003477 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003478 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003479
Steve Naroff4a746782008-01-09 22:43:08 +00003480 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003481 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003482#define TYPE(Class, Base)
3483#define ABSTRACT_TYPE(Class, Base)
3484#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3485#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3486#include "clang/AST/TypeNodes.def"
3487 assert(false && "Non-canonical and dependent types shouldn't get here");
3488 return QualType();
3489
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003490 case Type::LValueReference:
3491 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003492 case Type::MemberPointer:
3493 assert(false && "C++ should never be in mergeTypes");
3494 return QualType();
3495
3496 case Type::IncompleteArray:
3497 case Type::VariableArray:
3498 case Type::FunctionProto:
3499 case Type::ExtVector:
3500 case Type::ObjCQualifiedInterface:
3501 assert(false && "Types are eliminated above");
3502 return QualType();
3503
Chris Lattner1adb8832008-01-14 05:45:46 +00003504 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003505 {
3506 // Merge two pointer types, while trying to preserve typedef info
3507 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3508 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3509 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3510 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003511 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003512 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003513 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003514 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003515 return getPointerType(ResultType);
3516 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003517 case Type::BlockPointer:
3518 {
3519 // Merge two block pointer types, while trying to preserve typedef info
3520 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3521 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3522 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3523 if (ResultType.isNull()) return QualType();
3524 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3525 return LHS;
3526 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3527 return RHS;
3528 return getBlockPointerType(ResultType);
3529 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003530 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003531 {
3532 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3533 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3534 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3535 return QualType();
3536
3537 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3538 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3539 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3540 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003541 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3542 return LHS;
3543 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3544 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003545 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3546 ArrayType::ArraySizeModifier(), 0);
3547 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3548 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003549 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3550 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003551 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3552 return LHS;
3553 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3554 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003555 if (LVAT) {
3556 // FIXME: This isn't correct! But tricky to implement because
3557 // the array's size has to be the size of LHS, but the type
3558 // has to be different.
3559 return LHS;
3560 }
3561 if (RVAT) {
3562 // FIXME: This isn't correct! But tricky to implement because
3563 // the array's size has to be the size of RHS, but the type
3564 // has to be different.
3565 return RHS;
3566 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003567 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3568 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003569 return getIncompleteArrayType(ResultType,
3570 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003571 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003572 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003573 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003574 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003575 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003576 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003577 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003578 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003579 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003580 case Type::Complex:
3581 // Distinct complex types are incompatible.
3582 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003583 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003584 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003585 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3586 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003587 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003588 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003589 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003590 // FIXME: This should be type compatibility, e.g. whether
3591 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003592 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3593 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3594 if (LHSIface && RHSIface &&
3595 canAssignObjCInterfaces(LHSIface, RHSIface))
3596 return LHS;
3597
Eli Friedman3d815e72008-08-22 00:56:42 +00003598 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003599 }
Steve Naroff14108da2009-07-10 23:34:53 +00003600 case Type::ObjCObjectPointer: {
3601 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3602 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3603 return QualType();
3604
3605 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3606 RHS->getAsObjCObjectPointerType()))
3607 return LHS;
3608
Steve Naroffbc76dd02008-12-10 22:14:21 +00003609 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003610 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003611 case Type::FixedWidthInt:
3612 // Distinct fixed-width integers are not compatible.
3613 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003614 case Type::ExtQual:
3615 // FIXME: ExtQual types can be compatible even if they're not
3616 // identical!
3617 return QualType();
3618 // First attempt at an implementation, but I'm not really sure it's
3619 // right...
3620#if 0
3621 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3622 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3623 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3624 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3625 return QualType();
3626 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3627 LHSBase = QualType(LQual->getBaseType(), 0);
3628 RHSBase = QualType(RQual->getBaseType(), 0);
3629 ResultType = mergeTypes(LHSBase, RHSBase);
3630 if (ResultType.isNull()) return QualType();
3631 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3632 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3633 return LHS;
3634 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3635 return RHS;
3636 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3637 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3638 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3639 return ResultType;
3640#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003641
3642 case Type::TemplateSpecialization:
3643 assert(false && "Dependent types have no size");
3644 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003645 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003646
3647 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003648}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003649
Chris Lattner5426bf62008-04-07 07:01:58 +00003650//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003651// Integer Predicates
3652//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003653
Eli Friedmanad74a752008-06-28 06:23:08 +00003654unsigned ASTContext::getIntWidth(QualType T) {
3655 if (T == BoolTy)
3656 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003657 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3658 return FWIT->getWidth();
3659 }
3660 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003661 return (unsigned)getTypeSize(T);
3662}
3663
3664QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3665 assert(T->isSignedIntegerType() && "Unexpected type");
3666 if (const EnumType* ETy = T->getAsEnumType())
3667 T = ETy->getDecl()->getIntegerType();
3668 const BuiltinType* BTy = T->getAsBuiltinType();
3669 assert (BTy && "Unexpected signed integer type");
3670 switch (BTy->getKind()) {
3671 case BuiltinType::Char_S:
3672 case BuiltinType::SChar:
3673 return UnsignedCharTy;
3674 case BuiltinType::Short:
3675 return UnsignedShortTy;
3676 case BuiltinType::Int:
3677 return UnsignedIntTy;
3678 case BuiltinType::Long:
3679 return UnsignedLongTy;
3680 case BuiltinType::LongLong:
3681 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003682 case BuiltinType::Int128:
3683 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003684 default:
3685 assert(0 && "Unexpected signed integer type");
3686 return QualType();
3687 }
3688}
3689
Douglas Gregor2cf26342009-04-09 22:27:44 +00003690ExternalASTSource::~ExternalASTSource() { }
3691
3692void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003693
3694
3695//===----------------------------------------------------------------------===//
3696// Builtin Type Computation
3697//===----------------------------------------------------------------------===//
3698
3699/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3700/// pointer over the consumed characters. This returns the resultant type.
3701static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3702 ASTContext::GetBuiltinTypeError &Error,
3703 bool AllowTypeModifiers = true) {
3704 // Modifiers.
3705 int HowLong = 0;
3706 bool Signed = false, Unsigned = false;
3707
3708 // Read the modifiers first.
3709 bool Done = false;
3710 while (!Done) {
3711 switch (*Str++) {
3712 default: Done = true; --Str; break;
3713 case 'S':
3714 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3715 assert(!Signed && "Can't use 'S' modifier multiple times!");
3716 Signed = true;
3717 break;
3718 case 'U':
3719 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3720 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3721 Unsigned = true;
3722 break;
3723 case 'L':
3724 assert(HowLong <= 2 && "Can't have LLLL modifier");
3725 ++HowLong;
3726 break;
3727 }
3728 }
3729
3730 QualType Type;
3731
3732 // Read the base type.
3733 switch (*Str++) {
3734 default: assert(0 && "Unknown builtin type letter!");
3735 case 'v':
3736 assert(HowLong == 0 && !Signed && !Unsigned &&
3737 "Bad modifiers used with 'v'!");
3738 Type = Context.VoidTy;
3739 break;
3740 case 'f':
3741 assert(HowLong == 0 && !Signed && !Unsigned &&
3742 "Bad modifiers used with 'f'!");
3743 Type = Context.FloatTy;
3744 break;
3745 case 'd':
3746 assert(HowLong < 2 && !Signed && !Unsigned &&
3747 "Bad modifiers used with 'd'!");
3748 if (HowLong)
3749 Type = Context.LongDoubleTy;
3750 else
3751 Type = Context.DoubleTy;
3752 break;
3753 case 's':
3754 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3755 if (Unsigned)
3756 Type = Context.UnsignedShortTy;
3757 else
3758 Type = Context.ShortTy;
3759 break;
3760 case 'i':
3761 if (HowLong == 3)
3762 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3763 else if (HowLong == 2)
3764 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3765 else if (HowLong == 1)
3766 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3767 else
3768 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3769 break;
3770 case 'c':
3771 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3772 if (Signed)
3773 Type = Context.SignedCharTy;
3774 else if (Unsigned)
3775 Type = Context.UnsignedCharTy;
3776 else
3777 Type = Context.CharTy;
3778 break;
3779 case 'b': // boolean
3780 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3781 Type = Context.BoolTy;
3782 break;
3783 case 'z': // size_t.
3784 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3785 Type = Context.getSizeType();
3786 break;
3787 case 'F':
3788 Type = Context.getCFConstantStringType();
3789 break;
3790 case 'a':
3791 Type = Context.getBuiltinVaListType();
3792 assert(!Type.isNull() && "builtin va list type not initialized!");
3793 break;
3794 case 'A':
3795 // This is a "reference" to a va_list; however, what exactly
3796 // this means depends on how va_list is defined. There are two
3797 // different kinds of va_list: ones passed by value, and ones
3798 // passed by reference. An example of a by-value va_list is
3799 // x86, where va_list is a char*. An example of by-ref va_list
3800 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3801 // we want this argument to be a char*&; for x86-64, we want
3802 // it to be a __va_list_tag*.
3803 Type = Context.getBuiltinVaListType();
3804 assert(!Type.isNull() && "builtin va list type not initialized!");
3805 if (Type->isArrayType()) {
3806 Type = Context.getArrayDecayedType(Type);
3807 } else {
3808 Type = Context.getLValueReferenceType(Type);
3809 }
3810 break;
3811 case 'V': {
3812 char *End;
3813
3814 unsigned NumElements = strtoul(Str, &End, 10);
3815 assert(End != Str && "Missing vector size");
3816
3817 Str = End;
3818
3819 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3820 Type = Context.getVectorType(ElementType, NumElements);
3821 break;
3822 }
3823 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003824 Type = Context.getFILEType();
3825 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003826 Error = ASTContext::GE_Missing_FILE;
3827 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003828 } else {
3829 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003830 }
3831 }
3832 }
3833
3834 if (!AllowTypeModifiers)
3835 return Type;
3836
3837 Done = false;
3838 while (!Done) {
3839 switch (*Str++) {
3840 default: Done = true; --Str; break;
3841 case '*':
3842 Type = Context.getPointerType(Type);
3843 break;
3844 case '&':
3845 Type = Context.getLValueReferenceType(Type);
3846 break;
3847 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3848 case 'C':
3849 Type = Type.getQualifiedType(QualType::Const);
3850 break;
3851 }
3852 }
3853
3854 return Type;
3855}
3856
3857/// GetBuiltinType - Return the type for the specified builtin.
3858QualType ASTContext::GetBuiltinType(unsigned id,
3859 GetBuiltinTypeError &Error) {
3860 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3861
3862 llvm::SmallVector<QualType, 8> ArgTypes;
3863
3864 Error = GE_None;
3865 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3866 if (Error != GE_None)
3867 return QualType();
3868 while (TypeStr[0] && TypeStr[0] != '.') {
3869 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3870 if (Error != GE_None)
3871 return QualType();
3872
3873 // Do array -> pointer decay. The builtin should use the decayed type.
3874 if (Ty->isArrayType())
3875 Ty = getArrayDecayedType(Ty);
3876
3877 ArgTypes.push_back(Ty);
3878 }
3879
3880 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3881 "'.' should only occur at end of builtin type list!");
3882
3883 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3884 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3885 return getFunctionNoProtoType(ResType);
3886 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3887 TypeStr[0] == '.', 0);
3888}