blob: de4816c503be4f6bad529ef56aa0b2b1de13ed93 [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);
45 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000046 TUDecl = TranslationUnitDecl::Create(*this);
47}
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();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000194 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000195 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000196 ClassStructType = 0;
197
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000199
200 // void * type
201 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000202
203 // nullptr type (C++0x 2.14.7)
204 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205}
206
Douglas Gregor2e222532009-07-02 17:08:52 +0000207namespace {
208 class BeforeInTranslationUnit
209 : std::binary_function<SourceRange, SourceRange, bool> {
210 SourceManager *SourceMgr;
211
212 public:
213 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
214
215 bool operator()(SourceRange X, SourceRange Y) {
216 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
217 }
218 };
219}
220
221/// \brief Determine whether the given comment is a Doxygen-style comment.
222///
223/// \param Start the start of the comment text.
224///
225/// \param End the end of the comment text.
226///
227/// \param Member whether we want to check whether this is a member comment
228/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
229/// we only return true when we find a non-member comment.
230static bool
231isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
232 bool Member = false) {
233 const char *BufferStart
234 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
235 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
236 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
237
238 if (End - Start < 4)
239 return false;
240
241 assert(Start[0] == '/' && "Not a comment?");
242 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
243 return false;
244 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
245 return false;
246
247 return (Start[3] == '<') == Member;
248}
249
250/// \brief Retrieve the comment associated with the given declaration, if
251/// it has one.
252const char *ASTContext::getCommentForDecl(const Decl *D) {
253 if (!D)
254 return 0;
255
256 // Check whether we have cached a comment string for this declaration
257 // already.
258 llvm::DenseMap<const Decl *, std::string>::iterator Pos
259 = DeclComments.find(D);
260 if (Pos != DeclComments.end())
261 return Pos->second.c_str();
262
263 // If we have an external AST source and have not yet loaded comments from
264 // that source, do so now.
265 if (ExternalSource && !LoadedExternalComments) {
266 std::vector<SourceRange> LoadedComments;
267 ExternalSource->ReadComments(LoadedComments);
268
269 if (!LoadedComments.empty())
270 Comments.insert(Comments.begin(), LoadedComments.begin(),
271 LoadedComments.end());
272
273 LoadedExternalComments = true;
274 }
275
276 // If there are no comments anywhere, we won't find anything.
277 if (Comments.empty())
278 return 0;
279
280 // If the declaration doesn't map directly to a location in a file, we
281 // can't find the comment.
282 SourceLocation DeclStartLoc = D->getLocStart();
283 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
284 return 0;
285
286 // Find the comment that occurs just before this declaration.
287 std::vector<SourceRange>::iterator LastComment
288 = std::lower_bound(Comments.begin(), Comments.end(),
289 SourceRange(DeclStartLoc),
290 BeforeInTranslationUnit(&SourceMgr));
291
292 // Decompose the location for the start of the declaration and find the
293 // beginning of the file buffer.
294 std::pair<FileID, unsigned> DeclStartDecomp
295 = SourceMgr.getDecomposedLoc(DeclStartLoc);
296 const char *FileBufferStart
297 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
298
299 // First check whether we have a comment for a member.
300 if (LastComment != Comments.end() &&
301 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
302 isDoxygenComment(SourceMgr, *LastComment, true)) {
303 std::pair<FileID, unsigned> LastCommentEndDecomp
304 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
305 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
306 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
307 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
308 LastCommentEndDecomp.second)) {
309 // The Doxygen member comment comes after the declaration starts and
310 // is on the same line and in the same file as the declaration. This
311 // is the comment we want.
312 std::string &Result = DeclComments[D];
313 Result.append(FileBufferStart +
314 SourceMgr.getFileOffset(LastComment->getBegin()),
315 FileBufferStart + LastCommentEndDecomp.second + 1);
316 return Result.c_str();
317 }
318 }
319
320 if (LastComment == Comments.begin())
321 return 0;
322 --LastComment;
323
324 // Decompose the end of the comment.
325 std::pair<FileID, unsigned> LastCommentEndDecomp
326 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
327
328 // If the comment and the declaration aren't in the same file, then they
329 // aren't related.
330 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
331 return 0;
332
333 // Check that we actually have a Doxygen comment.
334 if (!isDoxygenComment(SourceMgr, *LastComment))
335 return 0;
336
337 // Compute the starting line for the declaration and for the end of the
338 // comment (this is expensive).
339 unsigned DeclStartLine
340 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
341 unsigned CommentEndLine
342 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
343 LastCommentEndDecomp.second);
344
345 // If the comment does not end on the line prior to the declaration, then
346 // the comment is not associated with the declaration at all.
347 if (CommentEndLine + 1 != DeclStartLine)
348 return 0;
349
350 // We have a comment, but there may be more comments on the previous lines.
351 // Keep looking so long as the comments are still Doxygen comments and are
352 // still adjacent.
353 unsigned ExpectedLine
354 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
355 std::vector<SourceRange>::iterator FirstComment = LastComment;
356 while (FirstComment != Comments.begin()) {
357 // Look at the previous comment
358 --FirstComment;
359 std::pair<FileID, unsigned> Decomp
360 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
361
362 // If this previous comment is in a different file, we're done.
363 if (Decomp.first != DeclStartDecomp.first) {
364 ++FirstComment;
365 break;
366 }
367
368 // If this comment is not a Doxygen comment, we're done.
369 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
370 ++FirstComment;
371 break;
372 }
373
374 // If the line number is not what we expected, we're done.
375 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
376 if (Line != ExpectedLine) {
377 ++FirstComment;
378 break;
379 }
380
381 // Set the next expected line number.
382 ExpectedLine
383 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
384 }
385
386 // The iterator range [FirstComment, LastComment] contains all of the
387 // BCPL comments that, together, are associated with this declaration.
388 // Form a single comment block string for this declaration that concatenates
389 // all of these comments.
390 std::string &Result = DeclComments[D];
391 while (FirstComment != LastComment) {
392 std::pair<FileID, unsigned> DecompStart
393 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
394 std::pair<FileID, unsigned> DecompEnd
395 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
396 Result.append(FileBufferStart + DecompStart.second,
397 FileBufferStart + DecompEnd.second + 1);
398 ++FirstComment;
399 }
400
401 // Append the last comment line.
402 Result.append(FileBufferStart +
403 SourceMgr.getFileOffset(LastComment->getBegin()),
404 FileBufferStart + LastCommentEndDecomp.second + 1);
405 return Result.c_str();
406}
407
Chris Lattner464175b2007-07-18 17:52:12 +0000408//===----------------------------------------------------------------------===//
409// Type Sizing and Analysis
410//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000411
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000412/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
413/// scalar floating point type.
414const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
415 const BuiltinType *BT = T->getAsBuiltinType();
416 assert(BT && "Not a floating point type!");
417 switch (BT->getKind()) {
418 default: assert(0 && "Not a floating point type!");
419 case BuiltinType::Float: return Target.getFloatFormat();
420 case BuiltinType::Double: return Target.getDoubleFormat();
421 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
422 }
423}
424
Chris Lattneraf707ab2009-01-24 21:53:27 +0000425/// getDeclAlign - Return a conservative estimate of the alignment of the
426/// specified decl. Note that bitfields do not have a valid alignment, so
427/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000428unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000429 unsigned Align = Target.getCharWidth();
430
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000431 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000432 Align = std::max(Align, AA->getAlignment());
433
Chris Lattneraf707ab2009-01-24 21:53:27 +0000434 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
435 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000436 if (const ReferenceType* RT = T->getAsReferenceType()) {
437 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000438 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000439 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
440 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000441 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
442 T = cast<ArrayType>(T)->getElementType();
443
444 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
445 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000446 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000447
448 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000449}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000450
Chris Lattnera7674d82007-07-13 22:13:22 +0000451/// getTypeSize - Return the size of the specified type, in bits. This method
452/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000453std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000454ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000455 uint64_t Width=0;
456 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000457 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000458#define TYPE(Class, Base)
459#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000460#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000461#define DEPENDENT_TYPE(Class, Base) case Type::Class:
462#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000463 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000464 break;
465
Chris Lattner692233e2007-07-13 22:27:08 +0000466 case Type::FunctionNoProto:
467 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000468 // GCC extension: alignof(function) = 32 bits
469 Width = 0;
470 Align = 32;
471 break;
472
Douglas Gregor72564e72009-02-26 23:50:07 +0000473 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000474 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000475 Width = 0;
476 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
477 break;
478
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000479 case Type::ConstantArrayWithExpr:
480 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000481 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000482 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000483
Chris Lattner98be4942008-03-05 18:54:05 +0000484 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000485 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000486 Align = EltInfo.second;
487 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000488 }
Nate Begeman213541a2008-04-18 23:10:10 +0000489 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000490 case Type::Vector: {
491 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000492 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000493 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000494 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000495 // If the alignment is not a power of 2, round up to the next power of 2.
496 // This happens for non-power-of-2 length vectors.
497 // FIXME: this should probably be a target property.
498 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000499 break;
500 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000501
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000502 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000503 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000504 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000505 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000506 // GCC extension: alignof(void) = 8 bits.
507 Width = 0;
508 Align = 8;
509 break;
510
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000511 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000512 Width = Target.getBoolWidth();
513 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000514 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000515 case BuiltinType::Char_S:
516 case BuiltinType::Char_U:
517 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000518 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000519 Width = Target.getCharWidth();
520 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000521 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000522 case BuiltinType::WChar:
523 Width = Target.getWCharWidth();
524 Align = Target.getWCharAlign();
525 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000526 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000527 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000528 Width = Target.getShortWidth();
529 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000530 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000531 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000532 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000533 Width = Target.getIntWidth();
534 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000535 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000536 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000537 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000538 Width = Target.getLongWidth();
539 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000540 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000541 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000542 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000543 Width = Target.getLongLongWidth();
544 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000545 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000546 case BuiltinType::Int128:
547 case BuiltinType::UInt128:
548 Width = 128;
549 Align = 128; // int128_t is 128-bit aligned on all targets.
550 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000551 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000552 Width = Target.getFloatWidth();
553 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 break;
555 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000556 Width = Target.getDoubleWidth();
557 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000558 break;
559 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000560 Width = Target.getLongDoubleWidth();
561 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000562 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000563 case BuiltinType::NullPtr:
564 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
565 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000566 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000567 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000568 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000569 case Type::FixedWidthInt:
570 // FIXME: This isn't precisely correct; the width/alignment should depend
571 // on the available types for the target
572 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000573 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000574 Align = Width;
575 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000576 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000577 // FIXME: Pointers into different addr spaces could have different sizes and
578 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000579 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000580 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000581 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000582 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000583 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000584 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000585 case Type::BlockPointer: {
586 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
587 Width = Target.getPointerWidth(AS);
588 Align = Target.getPointerAlign(AS);
589 break;
590 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000591 case Type::Pointer: {
592 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000593 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000594 Align = Target.getPointerAlign(AS);
595 break;
596 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000597 case Type::LValueReference:
598 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000599 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000600 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000601 // FIXME: This is wrong for struct layout: a reference in a struct has
602 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000603 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000604 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000605 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
606 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
607 // If we ever want to support other ABIs this needs to be abstracted.
608
Sebastian Redlf30208a2009-01-24 21:16:55 +0000609 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000610 std::pair<uint64_t, unsigned> PtrDiffInfo =
611 getTypeInfo(getPointerDiffType());
612 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000613 if (Pointee->isFunctionType())
614 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000615 Align = PtrDiffInfo.second;
616 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000617 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000618 case Type::Complex: {
619 // Complex types have the same alignment as their elements, but twice the
620 // size.
621 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000622 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000623 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000624 Align = EltInfo.second;
625 break;
626 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000627 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000628 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000629 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
630 Width = Layout.getSize();
631 Align = Layout.getAlignment();
632 break;
633 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000634 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000635 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000636 const TagType *TT = cast<TagType>(T);
637
638 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000639 Width = 1;
640 Align = 1;
641 break;
642 }
643
Daniel Dunbar1d751182008-11-08 05:48:37 +0000644 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000645 return getTypeInfo(ET->getDecl()->getIntegerType());
646
Daniel Dunbar1d751182008-11-08 05:48:37 +0000647 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000648 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
649 Width = Layout.getSize();
650 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000651 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000652 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000653
Douglas Gregor18857642009-04-30 17:32:17 +0000654 case Type::Typedef: {
655 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000656 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000657 Align = Aligned->getAlignment();
658 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
659 } else
660 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000661 break;
Chris Lattner71763312008-04-06 22:05:18 +0000662 }
Douglas Gregor18857642009-04-30 17:32:17 +0000663
664 case Type::TypeOfExpr:
665 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
666 .getTypePtr());
667
668 case Type::TypeOf:
669 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
670
Anders Carlsson395b4752009-06-24 19:06:50 +0000671 case Type::Decltype:
672 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
673 .getTypePtr());
674
Douglas Gregor18857642009-04-30 17:32:17 +0000675 case Type::QualifiedName:
676 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
677
678 case Type::TemplateSpecialization:
679 assert(getCanonicalType(T) != T &&
680 "Cannot request the size of a dependent type");
681 // FIXME: this is likely to be wrong once we support template
682 // aliases, since a template alias could refer to a typedef that
683 // has an __aligned__ attribute on it.
684 return getTypeInfo(getCanonicalType(T));
685 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000686
Chris Lattner464175b2007-07-18 17:52:12 +0000687 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000689}
690
Chris Lattner34ebde42009-01-27 18:08:34 +0000691/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
692/// type for the current target in bits. This can be different than the ABI
693/// alignment in cases where it is beneficial for performance to overalign
694/// a data type.
695unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
696 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000697
698 // Double and long long should be naturally aligned if possible.
699 if (const ComplexType* CT = T->getAsComplexType())
700 T = CT->getElementType().getTypePtr();
701 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
702 T->isSpecificBuiltinType(BuiltinType::LongLong))
703 return std::max(ABIAlign, (unsigned)getTypeSize(T));
704
Chris Lattner34ebde42009-01-27 18:08:34 +0000705 return ABIAlign;
706}
707
708
Devang Patel8b277042008-06-04 21:22:16 +0000709/// LayoutField - Field layout.
710void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000711 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000712 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000713 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000714 uint64_t FieldOffset = IsUnion ? 0 : Size;
715 uint64_t FieldSize;
716 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000717
718 // FIXME: Should this override struct packing? Probably we want to
719 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000720 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000721 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000722
723 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
724 // TODO: Need to check this algorithm on other targets!
725 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000726 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000727
728 std::pair<uint64_t, unsigned> FieldInfo =
729 Context.getTypeInfo(FD->getType());
730 uint64_t TypeSize = FieldInfo.first;
731
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000732 // Determine the alignment of this bitfield. The packing
733 // attributes define a maximum and the alignment attribute defines
734 // a minimum.
735 // FIXME: What is the right behavior when the specified alignment
736 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000737 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000738 if (FieldPacking)
739 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000740 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000741 FieldAlign = std::max(FieldAlign, AA->getAlignment());
742
743 // Check if we need to add padding to give the field the correct
744 // alignment.
745 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
746 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
747
748 // Padding members don't affect overall alignment
749 if (!FD->getIdentifier())
750 FieldAlign = 1;
751 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000752 if (FD->getType()->isIncompleteArrayType()) {
753 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000754 // query getTypeInfo about these, so we figure it out here.
755 // Flexible array members don't have any size, but they
756 // have to be aligned appropriately for their element type.
757 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000758 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000759 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000760 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
761 unsigned AS = RT->getPointeeType().getAddressSpace();
762 FieldSize = Context.Target.getPointerWidth(AS);
763 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000764 } else {
765 std::pair<uint64_t, unsigned> FieldInfo =
766 Context.getTypeInfo(FD->getType());
767 FieldSize = FieldInfo.first;
768 FieldAlign = FieldInfo.second;
769 }
770
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000771 // Determine the alignment of this bitfield. The packing
772 // attributes define a maximum and the alignment attribute defines
773 // a minimum. Additionally, the packing alignment must be at least
774 // a byte for non-bitfields.
775 //
776 // FIXME: What is the right behavior when the specified alignment
777 // is smaller than the specified packing?
778 if (FieldPacking)
779 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000780 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000781 FieldAlign = std::max(FieldAlign, AA->getAlignment());
782
783 // Round up the current record size to the field's alignment boundary.
784 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
785 }
786
787 // Place this field at the current location.
788 FieldOffsets[FieldNo] = FieldOffset;
789
790 // Reserve space for this field.
791 if (IsUnion) {
792 Size = std::max(Size, FieldSize);
793 } else {
794 Size = FieldOffset + FieldSize;
795 }
796
Daniel Dunbard6884a02009-05-04 05:16:21 +0000797 // Remember the next available offset.
798 NextOffset = Size;
799
Devang Patel8b277042008-06-04 21:22:16 +0000800 // Remember max struct/class alignment.
801 Alignment = std::max(Alignment, FieldAlign);
802}
803
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000804static void CollectLocalObjCIvars(ASTContext *Ctx,
805 const ObjCInterfaceDecl *OI,
806 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000807 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
808 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000809 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000810 if (!IVDecl->isInvalidDecl())
811 Fields.push_back(cast<FieldDecl>(IVDecl));
812 }
813}
814
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000815void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
816 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
817 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
818 CollectObjCIvars(SuperClass, Fields);
819 CollectLocalObjCIvars(this, OI, Fields);
820}
821
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000822/// ShallowCollectObjCIvars -
823/// Collect all ivars, including those synthesized, in the current class.
824///
825void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
826 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
827 bool CollectSynthesized) {
828 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
829 E = OI->ivar_end(); I != E; ++I) {
830 Ivars.push_back(*I);
831 }
832 if (CollectSynthesized)
833 CollectSynthesizedIvars(OI, Ivars);
834}
835
Fariborz Jahanian98200742009-05-12 18:14:29 +0000836void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
837 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000838 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
839 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000840 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
841 Ivars.push_back(Ivar);
842
843 // Also look into nested protocols.
844 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
845 E = PD->protocol_end(); P != E; ++P)
846 CollectProtocolSynthesizedIvars(*P, Ivars);
847}
848
849/// CollectSynthesizedIvars -
850/// This routine collect synthesized ivars for the designated class.
851///
852void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
853 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000854 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
855 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000856 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
857 Ivars.push_back(Ivar);
858 }
859 // Also look into interface's protocol list for properties declared
860 // in the protocol and whose ivars are synthesized.
861 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
862 PE = OI->protocol_end(); P != PE; ++P) {
863 ObjCProtocolDecl *PD = (*P);
864 CollectProtocolSynthesizedIvars(PD, Ivars);
865 }
866}
867
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000868unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
869 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000870 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
871 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000872 if ((*I)->getPropertyIvarDecl())
873 ++count;
874
875 // Also look into nested protocols.
876 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
877 E = PD->protocol_end(); P != E; ++P)
878 count += CountProtocolSynthesizedIvars(*P);
879 return count;
880}
881
882unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
883{
884 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000885 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
886 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000887 if ((*I)->getPropertyIvarDecl())
888 ++count;
889 }
890 // Also look into interface's protocol list for properties declared
891 // in the protocol and whose ivars are synthesized.
892 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
893 PE = OI->protocol_end(); P != PE; ++P) {
894 ObjCProtocolDecl *PD = (*P);
895 count += CountProtocolSynthesizedIvars(PD);
896 }
897 return count;
898}
899
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000900/// getInterfaceLayoutImpl - Get or compute information about the
901/// layout of the given interface.
902///
903/// \param Impl - If given, also include the layout of the interface's
904/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000905const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000906ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
907 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000908 assert(!D->isForwardDecl() && "Invalid interface decl!");
909
Devang Patel44a3dde2008-06-04 21:54:36 +0000910 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000911 ObjCContainerDecl *Key =
912 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
913 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
914 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000915
Daniel Dunbar453addb2009-05-03 11:16:44 +0000916 unsigned FieldCount = D->ivar_size();
917 // Add in synthesized ivar count if laying out an implementation.
918 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000919 unsigned SynthCount = CountSynthesizedIvars(D);
920 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000921 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000922 // entry. Note we can't cache this because we simply free all
923 // entries later; however we shouldn't look up implementations
924 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000925 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000926 return getObjCLayout(D, 0);
927 }
928
Devang Patel6a5a34c2008-06-06 02:14:01 +0000929 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000930 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000931 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
932 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000933
Daniel Dunbar913af352009-05-07 21:58:26 +0000934 // We start laying out ivars not at the end of the superclass
935 // structure, but at the next byte following the last field.
936 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000937
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000938 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000939 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000940 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000941 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000942 NewEntry->InitializeLayout(FieldCount);
943 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000944
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000945 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000946 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000947 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000948
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000949 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000950 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
951 AA->getAlignment()));
952
953 // Layout each ivar sequentially.
954 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000955 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
956 ShallowCollectObjCIvars(D, Ivars, Impl);
957 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
958 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
959
Devang Patel44a3dde2008-06-04 21:54:36 +0000960 // Finally, round the size of the total struct up to the alignment of the
961 // struct itself.
962 NewEntry->FinalizeLayout();
963 return *NewEntry;
964}
965
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000966const ASTRecordLayout &
967ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
968 return getObjCLayout(D, 0);
969}
970
971const ASTRecordLayout &
972ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
973 return getObjCLayout(D->getClassInterface(), D);
974}
975
Devang Patel88a981b2007-11-01 19:11:01 +0000976/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000977/// specified record (struct/union/class), which indicates its size and field
978/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000979const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000980 D = D->getDefinition(*this);
981 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000982
Chris Lattner464175b2007-07-18 17:52:12 +0000983 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000984 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000985 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000986
Devang Patel88a981b2007-11-01 19:11:01 +0000987 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
988 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
989 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000990 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000991
Douglas Gregore267ff32008-12-11 20:41:00 +0000992 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000993 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000994 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000995
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000996 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000997 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000998 StructPacking = PA->getAlignment();
999
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001000 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +00001001 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1002 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001003
Eli Friedman4bd998b2008-05-30 09:31:38 +00001004 // Layout each field, for now, just sequentially, respecting alignment. In
1005 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001006 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001007 for (RecordDecl::field_iterator Field = D->field_begin(),
1008 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001009 Field != FieldEnd; (void)++Field, ++FieldIdx)
1010 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001011
1012 // Finally, round the size of the total struct up to the alignment of the
1013 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001014 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001015 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001016}
1017
Chris Lattnera7674d82007-07-13 22:13:22 +00001018//===----------------------------------------------------------------------===//
1019// Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001022QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001023 QualType CanT = getCanonicalType(T);
1024 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001025 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001026
1027 // If we are composing extended qualifiers together, merge together into one
1028 // ExtQualType node.
1029 unsigned CVRQuals = T.getCVRQualifiers();
1030 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1031 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001032
Chris Lattnerb7d25532009-02-18 22:53:11 +00001033 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1034 // If this type already has an address space specified, it cannot get
1035 // another one.
1036 assert(EQT->getAddressSpace() == 0 &&
1037 "Type cannot be in multiple addr spaces!");
1038 GCAttr = EQT->getObjCGCAttr();
1039 TypeNode = EQT->getBaseType();
1040 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001041
Chris Lattnerb7d25532009-02-18 22:53:11 +00001042 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001043 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001044 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001045 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001046 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001047 return QualType(EXTQy, CVRQuals);
1048
Christopher Lambebb97e92008-02-04 02:31:56 +00001049 // If the base type isn't canonical, this won't be a canonical type either,
1050 // so fill in the canonical type field.
1051 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001052 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001053 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001054
Chris Lattnerb7d25532009-02-18 22:53:11 +00001055 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001056 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001057 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001058 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001059 ExtQualType *New =
1060 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001061 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001062 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001063 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001064}
1065
Chris Lattnerb7d25532009-02-18 22:53:11 +00001066QualType ASTContext::getObjCGCQualType(QualType T,
1067 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001068 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001069 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001070 return T;
1071
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001072 if (T->isPointerType()) {
1073 QualType Pointee = T->getAsPointerType()->getPointeeType();
1074 if (Pointee->isPointerType()) {
1075 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1076 return getPointerType(ResultType);
1077 }
1078 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001079 // If we are composing extended qualifiers together, merge together into one
1080 // ExtQualType node.
1081 unsigned CVRQuals = T.getCVRQualifiers();
1082 Type *TypeNode = T.getTypePtr();
1083 unsigned AddressSpace = 0;
1084
1085 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1086 // If this type already has an address space specified, it cannot get
1087 // another one.
1088 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1089 "Type cannot be in multiple addr spaces!");
1090 AddressSpace = EQT->getAddressSpace();
1091 TypeNode = EQT->getBaseType();
1092 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001093
1094 // Check if we've already instantiated an gc qual'd type of this type.
1095 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001096 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001097 void *InsertPos = 0;
1098 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001099 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001100
1101 // If the base type isn't canonical, this won't be a canonical type either,
1102 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001103 // FIXME: Isn't this also not canonical if the base type is a array
1104 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001105 QualType Canonical;
1106 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001107 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001108
Chris Lattnerb7d25532009-02-18 22:53:11 +00001109 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001110 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1111 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1112 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001113 ExtQualType *New =
1114 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001115 ExtQualTypes.InsertNode(New, InsertPos);
1116 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001117 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001118}
Chris Lattnera7674d82007-07-13 22:13:22 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120/// getComplexType - Return the uniqued reference to the type for a complex
1121/// number with the specified element type.
1122QualType ASTContext::getComplexType(QualType T) {
1123 // Unique pointers, to guarantee there is only one pointer of a particular
1124 // structure.
1125 llvm::FoldingSetNodeID ID;
1126 ComplexType::Profile(ID, T);
1127
1128 void *InsertPos = 0;
1129 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1130 return QualType(CT, 0);
1131
1132 // If the pointee type isn't canonical, this won't be a canonical type either,
1133 // so fill in the canonical type field.
1134 QualType Canonical;
1135 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001136 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001137
1138 // Get the new insert position for the node we care about.
1139 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001140 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 }
Steve Narofff83820b2009-01-27 22:08:43 +00001142 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 Types.push_back(New);
1144 ComplexTypes.InsertNode(New, InsertPos);
1145 return QualType(New, 0);
1146}
1147
Eli Friedmanf98aba32009-02-13 02:31:07 +00001148QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1149 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1150 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1151 FixedWidthIntType *&Entry = Map[Width];
1152 if (!Entry)
1153 Entry = new FixedWidthIntType(Width, Signed);
1154 return QualType(Entry, 0);
1155}
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
1157/// getPointerType - Return the uniqued reference to the type for a pointer to
1158/// the specified type.
1159QualType ASTContext::getPointerType(QualType T) {
1160 // Unique pointers, to guarantee there is only one pointer of a particular
1161 // structure.
1162 llvm::FoldingSetNodeID ID;
1163 PointerType::Profile(ID, T);
1164
1165 void *InsertPos = 0;
1166 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1167 return QualType(PT, 0);
1168
1169 // If the pointee type isn't canonical, this won't be a canonical type either,
1170 // so fill in the canonical type field.
1171 QualType Canonical;
1172 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001173 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001174
1175 // Get the new insert position for the node we care about.
1176 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001177 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 }
Steve Narofff83820b2009-01-27 22:08:43 +00001179 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 Types.push_back(New);
1181 PointerTypes.InsertNode(New, InsertPos);
1182 return QualType(New, 0);
1183}
1184
Steve Naroff5618bd42008-08-27 16:04:49 +00001185/// getBlockPointerType - Return the uniqued reference to the type for
1186/// a pointer to the specified block.
1187QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001188 assert(T->isFunctionType() && "block of function types only");
1189 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001190 // structure.
1191 llvm::FoldingSetNodeID ID;
1192 BlockPointerType::Profile(ID, T);
1193
1194 void *InsertPos = 0;
1195 if (BlockPointerType *PT =
1196 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1197 return QualType(PT, 0);
1198
Steve Naroff296e8d52008-08-28 19:20:44 +00001199 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001200 // type either so fill in the canonical type field.
1201 QualType Canonical;
1202 if (!T->isCanonical()) {
1203 Canonical = getBlockPointerType(getCanonicalType(T));
1204
1205 // Get the new insert position for the node we care about.
1206 BlockPointerType *NewIP =
1207 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001208 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001209 }
Steve Narofff83820b2009-01-27 22:08:43 +00001210 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001211 Types.push_back(New);
1212 BlockPointerTypes.InsertNode(New, InsertPos);
1213 return QualType(New, 0);
1214}
1215
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001216/// getLValueReferenceType - Return the uniqued reference to the type for an
1217/// lvalue reference to the specified type.
1218QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // Unique pointers, to guarantee there is only one pointer of a particular
1220 // structure.
1221 llvm::FoldingSetNodeID ID;
1222 ReferenceType::Profile(ID, T);
1223
1224 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001225 if (LValueReferenceType *RT =
1226 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // If the referencee type isn't canonical, this won't be a canonical type
1230 // either, so fill in the canonical type field.
1231 QualType Canonical;
1232 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001233 Canonical = getLValueReferenceType(getCanonicalType(T));
1234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001236 LValueReferenceType *NewIP =
1237 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001238 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 }
1240
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001241 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001243 LValueReferenceTypes.InsertNode(New, InsertPos);
1244 return QualType(New, 0);
1245}
1246
1247/// getRValueReferenceType - Return the uniqued reference to the type for an
1248/// rvalue reference to the specified type.
1249QualType ASTContext::getRValueReferenceType(QualType T) {
1250 // Unique pointers, to guarantee there is only one pointer of a particular
1251 // structure.
1252 llvm::FoldingSetNodeID ID;
1253 ReferenceType::Profile(ID, T);
1254
1255 void *InsertPos = 0;
1256 if (RValueReferenceType *RT =
1257 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1258 return QualType(RT, 0);
1259
1260 // If the referencee type isn't canonical, this won't be a canonical type
1261 // either, so fill in the canonical type field.
1262 QualType Canonical;
1263 if (!T->isCanonical()) {
1264 Canonical = getRValueReferenceType(getCanonicalType(T));
1265
1266 // Get the new insert position for the node we care about.
1267 RValueReferenceType *NewIP =
1268 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1269 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1270 }
1271
1272 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1273 Types.push_back(New);
1274 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 return QualType(New, 0);
1276}
1277
Sebastian Redlf30208a2009-01-24 21:16:55 +00001278/// getMemberPointerType - Return the uniqued reference to the type for a
1279/// member pointer to the specified type, in the specified class.
1280QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1281{
1282 // Unique pointers, to guarantee there is only one pointer of a particular
1283 // structure.
1284 llvm::FoldingSetNodeID ID;
1285 MemberPointerType::Profile(ID, T, Cls);
1286
1287 void *InsertPos = 0;
1288 if (MemberPointerType *PT =
1289 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1290 return QualType(PT, 0);
1291
1292 // If the pointee or class type isn't canonical, this won't be a canonical
1293 // type either, so fill in the canonical type field.
1294 QualType Canonical;
1295 if (!T->isCanonical()) {
1296 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1297
1298 // Get the new insert position for the node we care about.
1299 MemberPointerType *NewIP =
1300 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1301 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1302 }
Steve Narofff83820b2009-01-27 22:08:43 +00001303 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001304 Types.push_back(New);
1305 MemberPointerTypes.InsertNode(New, InsertPos);
1306 return QualType(New, 0);
1307}
1308
Steve Narofffb22d962007-08-30 01:06:46 +00001309/// getConstantArrayType - Return the unique reference to the type for an
1310/// array of the specified element type.
1311QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001312 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001313 ArrayType::ArraySizeModifier ASM,
1314 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001315 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1316 "Constant array of VLAs is illegal!");
1317
Chris Lattner38aeec72009-05-13 04:12:56 +00001318 // Convert the array size into a canonical width matching the pointer size for
1319 // the target.
1320 llvm::APInt ArySize(ArySizeIn);
1321 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1322
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001324 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001325
1326 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001327 if (ConstantArrayType *ATP =
1328 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 return QualType(ATP, 0);
1330
1331 // If the element type isn't canonical, this won't be a canonical type either,
1332 // so fill in the canonical type field.
1333 QualType Canonical;
1334 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001335 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001336 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001338 ConstantArrayType *NewIP =
1339 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001340 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 }
1342
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001343 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001344 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001345 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 Types.push_back(New);
1347 return QualType(New, 0);
1348}
1349
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001350/// getConstantArrayWithExprType - Return a reference to the type for
1351/// an array of the specified element type.
1352QualType
1353ASTContext::getConstantArrayWithExprType(QualType EltTy,
1354 const llvm::APInt &ArySizeIn,
1355 Expr *ArySizeExpr,
1356 ArrayType::ArraySizeModifier ASM,
1357 unsigned EltTypeQuals,
1358 SourceRange Brackets) {
1359 // Convert the array size into a canonical width matching the pointer
1360 // size for the target.
1361 llvm::APInt ArySize(ArySizeIn);
1362 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1363
1364 // Compute the canonical ConstantArrayType.
1365 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1366 ArySize, ASM, EltTypeQuals);
1367 // Since we don't unique expressions, it isn't possible to unique VLA's
1368 // that have an expression provided for their size.
1369 ConstantArrayWithExprType *New =
1370 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1371 ArySize, ArySizeExpr,
1372 ASM, EltTypeQuals, Brackets);
1373 Types.push_back(New);
1374 return QualType(New, 0);
1375}
1376
1377/// getConstantArrayWithoutExprType - Return a reference to the type for
1378/// an array of the specified element type.
1379QualType
1380ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1381 const llvm::APInt &ArySizeIn,
1382 ArrayType::ArraySizeModifier ASM,
1383 unsigned EltTypeQuals) {
1384 // Convert the array size into a canonical width matching the pointer
1385 // size for the target.
1386 llvm::APInt ArySize(ArySizeIn);
1387 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1388
1389 // Compute the canonical ConstantArrayType.
1390 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1391 ArySize, ASM, EltTypeQuals);
1392 ConstantArrayWithoutExprType *New =
1393 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1394 ArySize, ASM, EltTypeQuals);
1395 Types.push_back(New);
1396 return QualType(New, 0);
1397}
1398
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001399/// getVariableArrayType - Returns a non-unique reference to the type for a
1400/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001401QualType ASTContext::getVariableArrayType(QualType EltTy,
1402 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001403 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001404 unsigned EltTypeQuals,
1405 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001406 // Since we don't unique expressions, it isn't possible to unique VLA's
1407 // that have an expression provided for their size.
1408
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001409 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001410 new(*this,8)VariableArrayType(EltTy, QualType(),
1411 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001412
1413 VariableArrayTypes.push_back(New);
1414 Types.push_back(New);
1415 return QualType(New, 0);
1416}
1417
Douglas Gregor898574e2008-12-05 23:32:09 +00001418/// getDependentSizedArrayType - Returns a non-unique reference to
1419/// the type for a dependently-sized array of the specified element
1420/// type. FIXME: We will need these to be uniqued, or at least
1421/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001422QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1423 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001424 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001425 unsigned EltTypeQuals,
1426 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001427 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1428 "Size must be type- or value-dependent!");
1429
1430 // Since we don't unique expressions, it isn't possible to unique
1431 // dependently-sized array types.
1432
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001433 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001434 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1435 NumElts, ASM, EltTypeQuals,
1436 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001437
1438 DependentSizedArrayTypes.push_back(New);
1439 Types.push_back(New);
1440 return QualType(New, 0);
1441}
1442
Eli Friedmanc5773c42008-02-15 18:16:39 +00001443QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1444 ArrayType::ArraySizeModifier ASM,
1445 unsigned EltTypeQuals) {
1446 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001447 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001448
1449 void *InsertPos = 0;
1450 if (IncompleteArrayType *ATP =
1451 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1452 return QualType(ATP, 0);
1453
1454 // If the element type isn't canonical, this won't be a canonical type
1455 // either, so fill in the canonical type field.
1456 QualType Canonical;
1457
1458 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001459 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001460 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001461
1462 // Get the new insert position for the node we care about.
1463 IncompleteArrayType *NewIP =
1464 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001465 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001466 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001467
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001468 IncompleteArrayType *New
1469 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1470 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001471
1472 IncompleteArrayTypes.InsertNode(New, InsertPos);
1473 Types.push_back(New);
1474 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001475}
1476
Steve Naroff73322922007-07-18 18:00:27 +00001477/// getVectorType - Return the unique reference to a vector type of
1478/// the specified element type and size. VectorType must be a built-in type.
1479QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 BuiltinType *baseType;
1481
Chris Lattnerf52ab252008-04-06 22:59:24 +00001482 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001483 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001484
1485 // Check if we've already instantiated a vector of this type.
1486 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001487 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 void *InsertPos = 0;
1489 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(VTP, 0);
1491
1492 // If the element type isn't canonical, this won't be a canonical type either,
1493 // so fill in the canonical type field.
1494 QualType Canonical;
1495 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001496 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497
1498 // Get the new insert position for the node we care about.
1499 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
Steve Narofff83820b2009-01-27 22:08:43 +00001502 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 VectorTypes.InsertNode(New, InsertPos);
1504 Types.push_back(New);
1505 return QualType(New, 0);
1506}
1507
Nate Begeman213541a2008-04-18 23:10:10 +00001508/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001509/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001510QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001511 BuiltinType *baseType;
1512
Chris Lattnerf52ab252008-04-06 22:59:24 +00001513 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001514 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001515
1516 // Check if we've already instantiated a vector of this type.
1517 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001518 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001519 void *InsertPos = 0;
1520 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1521 return QualType(VTP, 0);
1522
1523 // If the element type isn't canonical, this won't be a canonical type either,
1524 // so fill in the canonical type field.
1525 QualType Canonical;
1526 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001527 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001528
1529 // Get the new insert position for the node we care about.
1530 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001531 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001532 }
Steve Narofff83820b2009-01-27 22:08:43 +00001533 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001534 VectorTypes.InsertNode(New, InsertPos);
1535 Types.push_back(New);
1536 return QualType(New, 0);
1537}
1538
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001539QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1540 Expr *SizeExpr,
1541 SourceLocation AttrLoc) {
1542 DependentSizedExtVectorType *New =
1543 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1544 SizeExpr, AttrLoc);
1545
1546 DependentSizedExtVectorTypes.push_back(New);
1547 Types.push_back(New);
1548 return QualType(New, 0);
1549}
1550
Douglas Gregor72564e72009-02-26 23:50:07 +00001551/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001552///
Douglas Gregor72564e72009-02-26 23:50:07 +00001553QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 // Unique functions, to guarantee there is only one function of a particular
1555 // structure.
1556 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001557 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001558
1559 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001560 if (FunctionNoProtoType *FT =
1561 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 return QualType(FT, 0);
1563
1564 QualType Canonical;
1565 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001566 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001567
1568 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001569 FunctionNoProtoType *NewIP =
1570 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001571 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 }
1573
Douglas Gregor72564e72009-02-26 23:50:07 +00001574 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001576 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 return QualType(New, 0);
1578}
1579
1580/// getFunctionType - Return a normal function type with a typed argument
1581/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001582QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001583 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001584 unsigned TypeQuals, bool hasExceptionSpec,
1585 bool hasAnyExceptionSpec, unsigned NumExs,
1586 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Unique functions, to guarantee there is only one function of a particular
1588 // structure.
1589 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001590 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001591 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1592 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593
1594 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001595 if (FunctionProtoType *FTP =
1596 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001598
1599 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001601 if (hasExceptionSpec)
1602 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1604 if (!ArgArray[i]->isCanonical())
1605 isCanonical = false;
1606
1607 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001608 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 QualType Canonical;
1610 if (!isCanonical) {
1611 llvm::SmallVector<QualType, 16> CanonicalArgs;
1612 CanonicalArgs.reserve(NumArgs);
1613 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001614 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001615
Chris Lattnerf52ab252008-04-06 22:59:24 +00001616 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001617 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001618 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001619
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001621 FunctionProtoType *NewIP =
1622 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001623 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001625
Douglas Gregor72564e72009-02-26 23:50:07 +00001626 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001627 // for two variable size arrays (for parameter and exception types) at the
1628 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001629 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001630 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1631 NumArgs*sizeof(QualType) +
1632 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001633 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001634 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1635 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001637 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 return QualType(FTP, 0);
1639}
1640
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001641/// getTypeDeclType - Return the unique reference to the type for the
1642/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001643QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001644 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001645 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1646
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001647 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001648 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001649 else if (isa<TemplateTypeParmDecl>(Decl)) {
1650 assert(false && "Template type parameter types are always available.");
1651 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001652 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001653
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001654 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001655 if (PrevDecl)
1656 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001657 else
1658 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001659 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001660 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1661 if (PrevDecl)
1662 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001663 else
1664 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001665 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001666 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001667 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001668
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001669 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001670 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001671}
1672
Reid Spencer5f016e22007-07-11 17:01:13 +00001673/// getTypedefType - Return the unique reference to the type for the
1674/// specified typename decl.
1675QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1676 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1677
Chris Lattnerf52ab252008-04-06 22:59:24 +00001678 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001679 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 Types.push_back(Decl->TypeForDecl);
1681 return QualType(Decl->TypeForDecl, 0);
1682}
1683
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001684/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001685/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001686QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001687 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1688
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001689 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1690 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001691 Types.push_back(Decl->TypeForDecl);
1692 return QualType(Decl->TypeForDecl, 0);
1693}
1694
Douglas Gregorfab9d672009-02-05 23:33:38 +00001695/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001696/// parameter or parameter pack with the given depth, index, and (optionally)
1697/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001698QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001699 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001700 IdentifierInfo *Name) {
1701 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001702 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001703 void *InsertPos = 0;
1704 TemplateTypeParmType *TypeParm
1705 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1706
1707 if (TypeParm)
1708 return QualType(TypeParm, 0);
1709
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001710 if (Name) {
1711 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1712 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1713 Name, Canon);
1714 } else
1715 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001716
1717 Types.push_back(TypeParm);
1718 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1719
1720 return QualType(TypeParm, 0);
1721}
1722
Douglas Gregor55f6b142009-02-09 18:46:07 +00001723QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001724ASTContext::getTemplateSpecializationType(TemplateName Template,
1725 const TemplateArgument *Args,
1726 unsigned NumArgs,
1727 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001728 if (!Canon.isNull())
1729 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001730
Douglas Gregor55f6b142009-02-09 18:46:07 +00001731 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001732 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001733
Douglas Gregor55f6b142009-02-09 18:46:07 +00001734 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001735 TemplateSpecializationType *Spec
1736 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001737
1738 if (Spec)
1739 return QualType(Spec, 0);
1740
Douglas Gregor7532dc62009-03-30 22:58:21 +00001741 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001742 sizeof(TemplateArgument) * NumArgs),
1743 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001744 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001745 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001746 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001747
1748 return QualType(Spec, 0);
1749}
1750
Douglas Gregore4e5b052009-03-19 00:18:19 +00001751QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001752ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001753 QualType NamedType) {
1754 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001755 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001756
1757 void *InsertPos = 0;
1758 QualifiedNameType *T
1759 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1760 if (T)
1761 return QualType(T, 0);
1762
Douglas Gregorab452ba2009-03-26 23:50:42 +00001763 T = new (*this) QualifiedNameType(NNS, NamedType,
1764 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001765 Types.push_back(T);
1766 QualifiedNameTypes.InsertNode(T, InsertPos);
1767 return QualType(T, 0);
1768}
1769
Douglas Gregord57959a2009-03-27 23:10:48 +00001770QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1771 const IdentifierInfo *Name,
1772 QualType Canon) {
1773 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1774
1775 if (Canon.isNull()) {
1776 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1777 if (CanonNNS != NNS)
1778 Canon = getTypenameType(CanonNNS, Name);
1779 }
1780
1781 llvm::FoldingSetNodeID ID;
1782 TypenameType::Profile(ID, NNS, Name);
1783
1784 void *InsertPos = 0;
1785 TypenameType *T
1786 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1787 if (T)
1788 return QualType(T, 0);
1789
1790 T = new (*this) TypenameType(NNS, Name, Canon);
1791 Types.push_back(T);
1792 TypenameTypes.InsertNode(T, InsertPos);
1793 return QualType(T, 0);
1794}
1795
Douglas Gregor17343172009-04-01 00:28:59 +00001796QualType
1797ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1798 const TemplateSpecializationType *TemplateId,
1799 QualType Canon) {
1800 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1801
1802 if (Canon.isNull()) {
1803 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1804 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1805 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1806 const TemplateSpecializationType *CanonTemplateId
1807 = CanonType->getAsTemplateSpecializationType();
1808 assert(CanonTemplateId &&
1809 "Canonical type must also be a template specialization type");
1810 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1811 }
1812 }
1813
1814 llvm::FoldingSetNodeID ID;
1815 TypenameType::Profile(ID, NNS, TemplateId);
1816
1817 void *InsertPos = 0;
1818 TypenameType *T
1819 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1820 if (T)
1821 return QualType(T, 0);
1822
1823 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1824 Types.push_back(T);
1825 TypenameTypes.InsertNode(T, InsertPos);
1826 return QualType(T, 0);
1827}
1828
Chris Lattner88cb27a2008-04-07 04:56:42 +00001829/// CmpProtocolNames - Comparison predicate for sorting protocols
1830/// alphabetically.
1831static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1832 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001833 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001834}
1835
1836static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1837 unsigned &NumProtocols) {
1838 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1839
1840 // Sort protocols, keyed by name.
1841 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1842
1843 // Remove duplicates.
1844 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1845 NumProtocols = ProtocolsEnd-Protocols;
1846}
1847
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001848/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1849/// the given interface decl and the conforming protocol list.
1850QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1851 ObjCProtocolDecl **Protocols,
1852 unsigned NumProtocols) {
1853 // Sort the protocol list alphabetically to canonicalize it.
1854 if (NumProtocols)
1855 SortAndUniqueProtocols(Protocols, NumProtocols);
1856
1857 llvm::FoldingSetNodeID ID;
1858 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1859
1860 void *InsertPos = 0;
1861 if (ObjCObjectPointerType *QT =
1862 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1863 return QualType(QT, 0);
1864
1865 // No Match;
1866 ObjCObjectPointerType *QType =
1867 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1868
1869 Types.push_back(QType);
1870 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1871 return QualType(QType, 0);
1872}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001873
Chris Lattner065f0d72008-04-07 04:44:08 +00001874/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1875/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001876QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1877 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001878 // Sort the protocol list alphabetically to canonicalize it.
1879 SortAndUniqueProtocols(Protocols, NumProtocols);
1880
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001881 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001882 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001883
1884 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 if (ObjCQualifiedInterfaceType *QT =
1886 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001887 return QualType(QT, 0);
1888
1889 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001890 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001891 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001892
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001893 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001895 return QualType(QType, 0);
1896}
1897
Douglas Gregor72564e72009-02-26 23:50:07 +00001898/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1899/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001900/// multiple declarations that refer to "typeof(x)" all contain different
1901/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1902/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001903QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001904 TypeOfExprType *toe;
1905 if (tofExpr->isTypeDependent())
1906 toe = new (*this, 8) TypeOfExprType(tofExpr);
1907 else {
1908 QualType Canonical = getCanonicalType(tofExpr->getType());
1909 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1910 }
Steve Naroff9752f252007-08-01 18:02:17 +00001911 Types.push_back(toe);
1912 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001913}
1914
Steve Naroff9752f252007-08-01 18:02:17 +00001915/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1916/// TypeOfType AST's. The only motivation to unique these nodes would be
1917/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1918/// an issue. This doesn't effect the type checker, since it operates
1919/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001920QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001921 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001922 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001923 Types.push_back(tot);
1924 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001925}
1926
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001927/// getDecltypeForExpr - Given an expr, will return the decltype for that
1928/// expression, according to the rules in C++0x [dcl.type.simple]p4
1929static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001930 if (e->isTypeDependent())
1931 return Context.DependentTy;
1932
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001933 // If e is an id expression or a class member access, decltype(e) is defined
1934 // as the type of the entity named by e.
1935 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1936 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1937 return VD->getType();
1938 }
1939 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1940 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1941 return FD->getType();
1942 }
1943 // If e is a function call or an invocation of an overloaded operator,
1944 // (parentheses around e are ignored), decltype(e) is defined as the
1945 // return type of that function.
1946 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1947 return CE->getCallReturnType();
1948
1949 QualType T = e->getType();
1950
1951 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1952 // defined as T&, otherwise decltype(e) is defined as T.
1953 if (e->isLvalue(Context) == Expr::LV_Valid)
1954 T = Context.getLValueReferenceType(T);
1955
1956 return T;
1957}
1958
Anders Carlsson395b4752009-06-24 19:06:50 +00001959/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1960/// DecltypeType AST's. The only motivation to unique these nodes would be
1961/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1962/// an issue. This doesn't effect the type checker, since it operates
1963/// on canonical type's (which are always unique).
1964QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001965 DecltypeType *dt;
1966 if (e->isTypeDependent()) // FIXME: canonicalize the expression
1967 dt = new (*this, 8) DecltypeType(e);
1968 else {
1969 QualType T = getDecltypeForExpr(e, *this);
1970 dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
1971 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001972 Types.push_back(dt);
1973 return QualType(dt, 0);
1974}
1975
Reid Spencer5f016e22007-07-11 17:01:13 +00001976/// getTagDeclType - Return the unique reference to the type for the
1977/// specified TagDecl (struct/union/class/enum) decl.
1978QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001979 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001980 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001981}
1982
1983/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1984/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1985/// needs to agree with the definition in <stddef.h>.
1986QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001987 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001988}
1989
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001990/// getSignedWCharType - Return the type of "signed wchar_t".
1991/// Used when in C++, as a GCC extension.
1992QualType ASTContext::getSignedWCharType() const {
1993 // FIXME: derive from "Target" ?
1994 return WCharTy;
1995}
1996
1997/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1998/// Used when in C++, as a GCC extension.
1999QualType ASTContext::getUnsignedWCharType() const {
2000 // FIXME: derive from "Target" ?
2001 return UnsignedIntTy;
2002}
2003
Chris Lattner8b9023b2007-07-13 03:05:23 +00002004/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2005/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2006QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002007 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002008}
2009
Chris Lattnere6327742008-04-02 05:18:44 +00002010//===----------------------------------------------------------------------===//
2011// Type Operators
2012//===----------------------------------------------------------------------===//
2013
Chris Lattner77c96472008-04-06 22:41:35 +00002014/// getCanonicalType - Return the canonical (structural) type corresponding to
2015/// the specified potentially non-canonical type. The non-canonical version
2016/// of a type may have many "decorated" versions of types. Decorators can
2017/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2018/// to be free of any of these, allowing two canonical types to be compared
2019/// for exact equality with a simple pointer comparison.
2020QualType ASTContext::getCanonicalType(QualType T) {
2021 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002022
2023 // If the result has type qualifiers, make sure to canonicalize them as well.
2024 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2025 if (TypeQuals == 0) return CanType;
2026
2027 // If the type qualifiers are on an array type, get the canonical type of the
2028 // array with the qualifiers applied to the element type.
2029 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2030 if (!AT)
2031 return CanType.getQualifiedType(TypeQuals);
2032
2033 // Get the canonical version of the element with the extra qualifiers on it.
2034 // This can recursively sink qualifiers through multiple levels of arrays.
2035 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2036 NewEltTy = getCanonicalType(NewEltTy);
2037
2038 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2039 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2040 CAT->getIndexTypeQualifier());
2041 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2042 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2043 IAT->getIndexTypeQualifier());
2044
Douglas Gregor898574e2008-12-05 23:32:09 +00002045 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002046 return getDependentSizedArrayType(NewEltTy,
2047 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002048 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002049 DSAT->getIndexTypeQualifier(),
2050 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002051
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002052 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002053 return getVariableArrayType(NewEltTy,
2054 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002055 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002056 VAT->getIndexTypeQualifier(),
2057 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002058}
2059
Douglas Gregor7da97d02009-05-10 22:57:19 +00002060Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00002061 if (!D)
2062 return 0;
2063
Douglas Gregor7da97d02009-05-10 22:57:19 +00002064 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2065 QualType T = getTagDeclType(Tag);
2066 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2067 ->getDecl());
2068 }
2069
2070 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2071 while (Template->getPreviousDeclaration())
2072 Template = Template->getPreviousDeclaration();
2073 return Template;
2074 }
2075
2076 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2077 while (Function->getPreviousDeclaration())
2078 Function = Function->getPreviousDeclaration();
2079 return const_cast<FunctionDecl *>(Function);
2080 }
2081
Douglas Gregor127102b2009-06-29 20:59:39 +00002082 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2083 while (FunTmpl->getPreviousDeclaration())
2084 FunTmpl = FunTmpl->getPreviousDeclaration();
2085 return FunTmpl;
2086 }
2087
Douglas Gregor7da97d02009-05-10 22:57:19 +00002088 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2089 while (Var->getPreviousDeclaration())
2090 Var = Var->getPreviousDeclaration();
2091 return const_cast<VarDecl *>(Var);
2092 }
2093
2094 return D;
2095}
2096
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002097TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2098 // If this template name refers to a template, the canonical
2099 // template name merely stores the template itself.
2100 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002101 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002102
2103 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2104 assert(DTN && "Non-dependent template names must refer to template decls.");
2105 return DTN->CanonicalTemplateName;
2106}
2107
Douglas Gregord57959a2009-03-27 23:10:48 +00002108NestedNameSpecifier *
2109ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2110 if (!NNS)
2111 return 0;
2112
2113 switch (NNS->getKind()) {
2114 case NestedNameSpecifier::Identifier:
2115 // Canonicalize the prefix but keep the identifier the same.
2116 return NestedNameSpecifier::Create(*this,
2117 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2118 NNS->getAsIdentifier());
2119
2120 case NestedNameSpecifier::Namespace:
2121 // A namespace is canonical; build a nested-name-specifier with
2122 // this namespace and no prefix.
2123 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2124
2125 case NestedNameSpecifier::TypeSpec:
2126 case NestedNameSpecifier::TypeSpecWithTemplate: {
2127 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2128 NestedNameSpecifier *Prefix = 0;
2129
2130 // FIXME: This isn't the right check!
2131 if (T->isDependentType())
2132 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2133
2134 return NestedNameSpecifier::Create(*this, Prefix,
2135 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2136 T.getTypePtr());
2137 }
2138
2139 case NestedNameSpecifier::Global:
2140 // The global specifier is canonical and unique.
2141 return NNS;
2142 }
2143
2144 // Required to silence a GCC warning
2145 return 0;
2146}
2147
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002148
2149const ArrayType *ASTContext::getAsArrayType(QualType T) {
2150 // Handle the non-qualified case efficiently.
2151 if (T.getCVRQualifiers() == 0) {
2152 // Handle the common positive case fast.
2153 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2154 return AT;
2155 }
2156
2157 // Handle the common negative case fast, ignoring CVR qualifiers.
2158 QualType CType = T->getCanonicalTypeInternal();
2159
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002160 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002161 // test.
2162 if (!isa<ArrayType>(CType) &&
2163 !isa<ArrayType>(CType.getUnqualifiedType()))
2164 return 0;
2165
2166 // Apply any CVR qualifiers from the array type to the element type. This
2167 // implements C99 6.7.3p8: "If the specification of an array type includes
2168 // any type qualifiers, the element type is so qualified, not the array type."
2169
2170 // If we get here, we either have type qualifiers on the type, or we have
2171 // sugar such as a typedef in the way. If we have type qualifiers on the type
2172 // we must propagate them down into the elemeng type.
2173 unsigned CVRQuals = T.getCVRQualifiers();
2174 unsigned AddrSpace = 0;
2175 Type *Ty = T.getTypePtr();
2176
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002177 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002178 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002179 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2180 AddrSpace = EXTQT->getAddressSpace();
2181 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002182 } else {
2183 T = Ty->getDesugaredType();
2184 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2185 break;
2186 CVRQuals |= T.getCVRQualifiers();
2187 Ty = T.getTypePtr();
2188 }
2189 }
2190
2191 // If we have a simple case, just return now.
2192 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2193 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2194 return ATy;
2195
2196 // Otherwise, we have an array and we have qualifiers on it. Push the
2197 // qualifiers into the array element type and return a new array type.
2198 // Get the canonical version of the element with the extra qualifiers on it.
2199 // This can recursively sink qualifiers through multiple levels of arrays.
2200 QualType NewEltTy = ATy->getElementType();
2201 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002202 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002203 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2204
2205 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2206 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2207 CAT->getSizeModifier(),
2208 CAT->getIndexTypeQualifier()));
2209 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2210 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2211 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002212 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002213
Douglas Gregor898574e2008-12-05 23:32:09 +00002214 if (const DependentSizedArrayType *DSAT
2215 = dyn_cast<DependentSizedArrayType>(ATy))
2216 return cast<ArrayType>(
2217 getDependentSizedArrayType(NewEltTy,
2218 DSAT->getSizeExpr(),
2219 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002220 DSAT->getIndexTypeQualifier(),
2221 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002222
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002223 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002224 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2225 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002226 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002227 VAT->getIndexTypeQualifier(),
2228 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002229}
2230
2231
Chris Lattnere6327742008-04-02 05:18:44 +00002232/// getArrayDecayedType - Return the properly qualified result of decaying the
2233/// specified array type to a pointer. This operation is non-trivial when
2234/// handling typedefs etc. The canonical type of "T" must be an array type,
2235/// this returns a pointer to a properly qualified element of the array.
2236///
2237/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2238QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002239 // Get the element type with 'getAsArrayType' so that we don't lose any
2240 // typedefs in the element type of the array. This also handles propagation
2241 // of type qualifiers from the array type into the element type if present
2242 // (C99 6.7.3p8).
2243 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2244 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002245
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002246 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002247
2248 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002249 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002250}
2251
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002252QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002253 QualType ElemTy = VAT->getElementType();
2254
2255 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2256 return getBaseElementType(VAT);
2257
2258 return ElemTy;
2259}
2260
Reid Spencer5f016e22007-07-11 17:01:13 +00002261/// getFloatingRank - Return a relative rank for floating point types.
2262/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002263static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002264 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002266
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002267 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002268 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002269 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002270 case BuiltinType::Float: return FloatRank;
2271 case BuiltinType::Double: return DoubleRank;
2272 case BuiltinType::LongDouble: return LongDoubleRank;
2273 }
2274}
2275
Steve Naroff716c7302007-08-27 01:41:48 +00002276/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2277/// point or a complex type (based on typeDomain/typeSize).
2278/// 'typeDomain' is a real floating point or complex type.
2279/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002280QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2281 QualType Domain) const {
2282 FloatingRank EltRank = getFloatingRank(Size);
2283 if (Domain->isComplexType()) {
2284 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002285 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002286 case FloatRank: return FloatComplexTy;
2287 case DoubleRank: return DoubleComplexTy;
2288 case LongDoubleRank: return LongDoubleComplexTy;
2289 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 }
Chris Lattner1361b112008-04-06 23:58:54 +00002291
2292 assert(Domain->isRealFloatingType() && "Unknown domain!");
2293 switch (EltRank) {
2294 default: assert(0 && "getFloatingRank(): illegal value for rank");
2295 case FloatRank: return FloatTy;
2296 case DoubleRank: return DoubleTy;
2297 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002298 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002299}
2300
Chris Lattner7cfeb082008-04-06 23:55:33 +00002301/// getFloatingTypeOrder - Compare the rank of the two specified floating
2302/// point types, ignoring the domain of the type (i.e. 'double' ==
2303/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2304/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002305int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2306 FloatingRank LHSR = getFloatingRank(LHS);
2307 FloatingRank RHSR = getFloatingRank(RHS);
2308
2309 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002310 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002311 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002312 return 1;
2313 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002314}
2315
Chris Lattnerf52ab252008-04-06 22:59:24 +00002316/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2317/// routine will assert if passed a built-in type that isn't an integer or enum,
2318/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002319unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002320 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002321 if (EnumType* ET = dyn_cast<EnumType>(T))
2322 T = ET->getDecl()->getIntegerType().getTypePtr();
2323
Eli Friedmana3426752009-07-05 23:44:27 +00002324 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2325 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2326
Eli Friedmanf98aba32009-02-13 02:31:07 +00002327 // There are two things which impact the integer rank: the width, and
2328 // the ordering of builtins. The builtin ordering is encoded in the
2329 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002330 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002331 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002332
Chris Lattnerf52ab252008-04-06 22:59:24 +00002333 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002334 default: assert(0 && "getIntegerRank(): not a built-in integer");
2335 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002336 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002337 case BuiltinType::Char_S:
2338 case BuiltinType::Char_U:
2339 case BuiltinType::SChar:
2340 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002341 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002342 case BuiltinType::Short:
2343 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002344 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002345 case BuiltinType::Int:
2346 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002347 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002348 case BuiltinType::Long:
2349 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002350 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002351 case BuiltinType::LongLong:
2352 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002353 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002354 case BuiltinType::Int128:
2355 case BuiltinType::UInt128:
2356 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002357 }
2358}
2359
Chris Lattner7cfeb082008-04-06 23:55:33 +00002360/// getIntegerTypeOrder - Returns the highest ranked integer type:
2361/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2362/// LHS < RHS, return -1.
2363int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002364 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2365 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002366 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002367
Chris Lattnerf52ab252008-04-06 22:59:24 +00002368 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2369 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002370
Chris Lattner7cfeb082008-04-06 23:55:33 +00002371 unsigned LHSRank = getIntegerRank(LHSC);
2372 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002373
Chris Lattner7cfeb082008-04-06 23:55:33 +00002374 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2375 if (LHSRank == RHSRank) return 0;
2376 return LHSRank > RHSRank ? 1 : -1;
2377 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002378
Chris Lattner7cfeb082008-04-06 23:55:33 +00002379 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2380 if (LHSUnsigned) {
2381 // If the unsigned [LHS] type is larger, return it.
2382 if (LHSRank >= RHSRank)
2383 return 1;
2384
2385 // If the signed type can represent all values of the unsigned type, it
2386 // wins. Because we are dealing with 2's complement and types that are
2387 // powers of two larger than each other, this is always safe.
2388 return -1;
2389 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002390
Chris Lattner7cfeb082008-04-06 23:55:33 +00002391 // If the unsigned [RHS] type is larger, return it.
2392 if (RHSRank >= LHSRank)
2393 return -1;
2394
2395 // If the signed type can represent all values of the unsigned type, it
2396 // wins. Because we are dealing with 2's complement and types that are
2397 // powers of two larger than each other, this is always safe.
2398 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002399}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002400
2401// getCFConstantStringType - Return the type used for constant CFStrings.
2402QualType ASTContext::getCFConstantStringType() {
2403 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002404 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002405 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002406 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002407 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002408
2409 // const int *isa;
2410 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002411 // int flags;
2412 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002413 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002414 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002415 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002416 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002417
Anders Carlsson71993dd2007-08-17 05:31:46 +00002418 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002419 for (unsigned i = 0; i < 4; ++i) {
2420 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2421 SourceLocation(), 0,
2422 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002423 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002424 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002425 }
2426
2427 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002428 }
2429
2430 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002431}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002432
Douglas Gregor319ac892009-04-23 22:29:11 +00002433void ASTContext::setCFConstantStringType(QualType T) {
2434 const RecordType *Rec = T->getAsRecordType();
2435 assert(Rec && "Invalid CFConstantStringType");
2436 CFConstantStringTypeDecl = Rec->getDecl();
2437}
2438
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002439QualType ASTContext::getObjCFastEnumerationStateType()
2440{
2441 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002442 ObjCFastEnumerationStateTypeDecl =
2443 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2444 &Idents.get("__objcFastEnumerationState"));
2445
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002446 QualType FieldTypes[] = {
2447 UnsignedLongTy,
2448 getPointerType(ObjCIdType),
2449 getPointerType(UnsignedLongTy),
2450 getConstantArrayType(UnsignedLongTy,
2451 llvm::APInt(32, 5), ArrayType::Normal, 0)
2452 };
2453
Douglas Gregor44b43212008-12-11 16:49:14 +00002454 for (size_t i = 0; i < 4; ++i) {
2455 FieldDecl *Field = FieldDecl::Create(*this,
2456 ObjCFastEnumerationStateTypeDecl,
2457 SourceLocation(), 0,
2458 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002459 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002460 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002461 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002462
Douglas Gregor44b43212008-12-11 16:49:14 +00002463 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002464 }
2465
2466 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2467}
2468
Douglas Gregor319ac892009-04-23 22:29:11 +00002469void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2470 const RecordType *Rec = T->getAsRecordType();
2471 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2472 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2473}
2474
Anders Carlssone8c49532007-10-29 06:33:42 +00002475// This returns true if a type has been typedefed to BOOL:
2476// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002477static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002478 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002479 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2480 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002481
2482 return false;
2483}
2484
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002485/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002486/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002487int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002488 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002489
2490 // Make all integer and enum types at least as large as an int
2491 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002492 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002493 // Treat arrays as pointers, since that's how they're passed in.
2494 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002495 sz = getTypeSize(VoidPtrTy);
2496 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002497}
2498
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002499/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002500/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002501void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002502 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002503 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002504 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002506 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002507 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002508 // Compute size of all parameters.
2509 // Start with computing size of a pointer in number of bytes.
2510 // FIXME: There might(should) be a better way of doing this computation!
2511 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002512 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002513 // The first two arguments (self and _cmd) are pointers; account for
2514 // their size.
2515 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002516 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2517 E = Decl->param_end(); PI != E; ++PI) {
2518 QualType PType = (*PI)->getType();
2519 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002520 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002521 ParmOffset += sz;
2522 }
2523 S += llvm::utostr(ParmOffset);
2524 S += "@0:";
2525 S += llvm::utostr(PtrSize);
2526
2527 // Argument types.
2528 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002529 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2530 E = Decl->param_end(); PI != E; ++PI) {
2531 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002532 QualType PType = PVDecl->getOriginalType();
2533 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002534 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2535 // Use array's original type only if it has known number of
2536 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002537 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002538 PType = PVDecl->getType();
2539 } else if (PType->isFunctionType())
2540 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002541 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002542 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002543 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002544 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002545 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002547 }
2548}
2549
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002550/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002551/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002552/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2553/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002554/// Property attributes are stored as a comma-delimited C string. The simple
2555/// attributes readonly and bycopy are encoded as single characters. The
2556/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2557/// encoded as single characters, followed by an identifier. Property types
2558/// are also encoded as a parametrized attribute. The characters used to encode
2559/// these attributes are defined by the following enumeration:
2560/// @code
2561/// enum PropertyAttributes {
2562/// kPropertyReadOnly = 'R', // property is read-only.
2563/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2564/// kPropertyByref = '&', // property is a reference to the value last assigned
2565/// kPropertyDynamic = 'D', // property is dynamic
2566/// kPropertyGetter = 'G', // followed by getter selector name
2567/// kPropertySetter = 'S', // followed by setter selector name
2568/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2569/// kPropertyType = 't' // followed by old-style type encoding.
2570/// kPropertyWeak = 'W' // 'weak' property
2571/// kPropertyStrong = 'P' // property GC'able
2572/// kPropertyNonAtomic = 'N' // property non-atomic
2573/// };
2574/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002575void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2576 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002577 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002578 // Collect information from the property implementation decl(s).
2579 bool Dynamic = false;
2580 ObjCPropertyImplDecl *SynthesizePID = 0;
2581
2582 // FIXME: Duplicated code due to poor abstraction.
2583 if (Container) {
2584 if (const ObjCCategoryImplDecl *CID =
2585 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2586 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002587 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002588 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002589 ObjCPropertyImplDecl *PID = *i;
2590 if (PID->getPropertyDecl() == PD) {
2591 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2592 Dynamic = true;
2593 } else {
2594 SynthesizePID = PID;
2595 }
2596 }
2597 }
2598 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002599 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002600 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002601 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002602 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002603 ObjCPropertyImplDecl *PID = *i;
2604 if (PID->getPropertyDecl() == PD) {
2605 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2606 Dynamic = true;
2607 } else {
2608 SynthesizePID = PID;
2609 }
2610 }
2611 }
2612 }
2613 }
2614
2615 // FIXME: This is not very efficient.
2616 S = "T";
2617
2618 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002619 // GCC has some special rules regarding encoding of properties which
2620 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002621 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002622 true /* outermost type */,
2623 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002624
2625 if (PD->isReadOnly()) {
2626 S += ",R";
2627 } else {
2628 switch (PD->getSetterKind()) {
2629 case ObjCPropertyDecl::Assign: break;
2630 case ObjCPropertyDecl::Copy: S += ",C"; break;
2631 case ObjCPropertyDecl::Retain: S += ",&"; break;
2632 }
2633 }
2634
2635 // It really isn't clear at all what this means, since properties
2636 // are "dynamic by default".
2637 if (Dynamic)
2638 S += ",D";
2639
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002640 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2641 S += ",N";
2642
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002643 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2644 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002645 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002646 }
2647
2648 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2649 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002650 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002651 }
2652
2653 if (SynthesizePID) {
2654 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2655 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002656 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002657 }
2658
2659 // FIXME: OBJCGC: weak & strong
2660}
2661
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002662/// getLegacyIntegralTypeEncoding -
2663/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002664/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002665/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2666///
2667void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2668 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2669 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002670 if (BT->getKind() == BuiltinType::ULong &&
2671 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002672 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002673 else
2674 if (BT->getKind() == BuiltinType::Long &&
2675 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002676 PointeeTy = IntTy;
2677 }
2678 }
2679}
2680
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002681void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002682 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002683 // We follow the behavior of gcc, expanding structures which are
2684 // directly pointed to, and expanding embedded structures. Note that
2685 // these rules are sufficient to prevent recursive encoding of the
2686 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002687 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2688 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002689}
2690
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002691static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002692 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002693 const Expr *E = FD->getBitWidth();
2694 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2695 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002696 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002697 S += 'b';
2698 S += llvm::utostr(N);
2699}
2700
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002701void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2702 bool ExpandPointedToStructures,
2703 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002704 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002705 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002706 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002707 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002708 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002709 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002710 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002711 else {
2712 char encoding;
2713 switch (BT->getKind()) {
2714 default: assert(0 && "Unhandled builtin type kind");
2715 case BuiltinType::Void: encoding = 'v'; break;
2716 case BuiltinType::Bool: encoding = 'B'; break;
2717 case BuiltinType::Char_U:
2718 case BuiltinType::UChar: encoding = 'C'; break;
2719 case BuiltinType::UShort: encoding = 'S'; break;
2720 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002721 case BuiltinType::ULong:
2722 encoding =
2723 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2724 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002725 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002726 case BuiltinType::ULongLong: encoding = 'Q'; break;
2727 case BuiltinType::Char_S:
2728 case BuiltinType::SChar: encoding = 'c'; break;
2729 case BuiltinType::Short: encoding = 's'; break;
2730 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002731 case BuiltinType::Long:
2732 encoding =
2733 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2734 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002735 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002736 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002737 case BuiltinType::Float: encoding = 'f'; break;
2738 case BuiltinType::Double: encoding = 'd'; break;
2739 case BuiltinType::LongDouble: encoding = 'd'; break;
2740 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002741
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002742 S += encoding;
2743 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002744 } else if (const ComplexType *CT = T->getAsComplexType()) {
2745 S += 'j';
2746 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2747 false);
2748 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002749 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2750 ExpandPointedToStructures,
2751 ExpandStructures, FD);
2752 if (FD || EncodingProperty) {
2753 // Note that we do extended encoding of protocol qualifer list
2754 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002755 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002756 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002757 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002758 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002759 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002760 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002761 S += '>';
2762 }
2763 S += '"';
2764 }
2765 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002766 }
2767 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002768 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002769 bool isReadOnly = false;
2770 // For historical/compatibility reasons, the read-only qualifier of the
2771 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2772 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2773 // Also, do not emit the 'r' for anything but the outermost type!
2774 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2775 if (OutermostType && T.isConstQualified()) {
2776 isReadOnly = true;
2777 S += 'r';
2778 }
2779 }
2780 else if (OutermostType) {
2781 QualType P = PointeeTy;
2782 while (P->getAsPointerType())
2783 P = P->getAsPointerType()->getPointeeType();
2784 if (P.isConstQualified()) {
2785 isReadOnly = true;
2786 S += 'r';
2787 }
2788 }
2789 if (isReadOnly) {
2790 // Another legacy compatibility encoding. Some ObjC qualifier and type
2791 // combinations need to be rearranged.
2792 // Rewrite "in const" from "nr" to "rn"
2793 const char * s = S.c_str();
2794 int len = S.length();
2795 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2796 std::string replace = "rn";
2797 S.replace(S.end()-2, S.end(), replace);
2798 }
2799 }
Steve Naroff389bf462009-02-12 17:52:19 +00002800 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002801 S += '@';
2802 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002803 }
2804 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002805 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002806 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002807 // Another historical/compatibility reason.
2808 // We encode the underlying type which comes out as
2809 // {...};
2810 S += '^';
2811 getObjCEncodingForTypeImpl(PointeeTy, S,
2812 false, ExpandPointedToStructures,
2813 NULL);
2814 return;
2815 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002816 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002817 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002818 const ObjCInterfaceType *OIT =
2819 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002820 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002821 S += '"';
2822 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002823 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2824 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002825 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002826 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002827 S += '>';
2828 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002829 S += '"';
2830 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002831 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002832 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002833 S += '#';
2834 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002835 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002836 S += ':';
2837 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002838 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002839
2840 if (PointeeTy->isCharType()) {
2841 // char pointer types should be encoded as '*' unless it is a
2842 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002843 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002844 S += '*';
2845 return;
2846 }
2847 }
2848
2849 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002850 getLegacyIntegralTypeEncoding(PointeeTy);
2851
2852 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002853 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002854 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002855 } else if (const ArrayType *AT =
2856 // Ignore type qualifiers etc.
2857 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002858 if (isa<IncompleteArrayType>(AT)) {
2859 // Incomplete arrays are encoded as a pointer to the array element.
2860 S += '^';
2861
2862 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2863 false, ExpandStructures, FD);
2864 } else {
2865 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002866
Anders Carlsson559a8332009-02-22 01:38:57 +00002867 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2868 S += llvm::utostr(CAT->getSize().getZExtValue());
2869 else {
2870 //Variable length arrays are encoded as a regular array with 0 elements.
2871 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2872 S += '0';
2873 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002874
Anders Carlsson559a8332009-02-22 01:38:57 +00002875 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2876 false, ExpandStructures, FD);
2877 S += ']';
2878 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002879 } else if (T->getAsFunctionType()) {
2880 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002881 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002882 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002883 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002884 // Anonymous structures print as '?'
2885 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2886 S += II->getName();
2887 } else {
2888 S += '?';
2889 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002890 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002891 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002892 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2893 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002894 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002895 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002896 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002897 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002898 S += '"';
2899 }
2900
2901 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002902 if (Field->isBitField()) {
2903 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2904 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002905 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002906 QualType qt = Field->getType();
2907 getLegacyIntegralTypeEncoding(qt);
2908 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002909 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002910 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002911 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002912 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002913 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002914 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002915 if (FD && FD->isBitField())
2916 EncodeBitField(this, S, FD);
2917 else
2918 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002919 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002920 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002921 } else if (T->isObjCInterfaceType()) {
2922 // @encode(class_name)
2923 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2924 S += '{';
2925 const IdentifierInfo *II = OI->getIdentifier();
2926 S += II->getName();
2927 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002928 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002929 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002930 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002931 if (RecFields[i]->isBitField())
2932 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2933 RecFields[i]);
2934 else
2935 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2936 FD);
2937 }
2938 S += '}';
2939 }
2940 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002941 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002942}
2943
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002944void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002945 std::string& S) const {
2946 if (QT & Decl::OBJC_TQ_In)
2947 S += 'n';
2948 if (QT & Decl::OBJC_TQ_Inout)
2949 S += 'N';
2950 if (QT & Decl::OBJC_TQ_Out)
2951 S += 'o';
2952 if (QT & Decl::OBJC_TQ_Bycopy)
2953 S += 'O';
2954 if (QT & Decl::OBJC_TQ_Byref)
2955 S += 'R';
2956 if (QT & Decl::OBJC_TQ_Oneway)
2957 S += 'V';
2958}
2959
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002960void ASTContext::setBuiltinVaListType(QualType T)
2961{
2962 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2963
2964 BuiltinVaListType = T;
2965}
2966
Douglas Gregor319ac892009-04-23 22:29:11 +00002967void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002968{
Douglas Gregor319ac892009-04-23 22:29:11 +00002969 ObjCIdType = T;
2970
2971 const TypedefType *TT = T->getAsTypedefType();
2972 if (!TT)
2973 return;
2974
2975 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002976
2977 // typedef struct objc_object *id;
2978 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002979 // User error - caller will issue diagnostics.
2980 if (!ptr)
2981 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002982 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002983 // User error - caller will issue diagnostics.
2984 if (!rec)
2985 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002986 IdStructType = rec;
2987}
2988
Douglas Gregor319ac892009-04-23 22:29:11 +00002989void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002990{
Douglas Gregor319ac892009-04-23 22:29:11 +00002991 ObjCSelType = T;
2992
2993 const TypedefType *TT = T->getAsTypedefType();
2994 if (!TT)
2995 return;
2996 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002997
2998 // typedef struct objc_selector *SEL;
2999 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003000 if (!ptr)
3001 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003002 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003003 if (!rec)
3004 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003005 SelStructType = rec;
3006}
3007
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003008void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003009{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003010 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003011}
3012
Douglas Gregor319ac892009-04-23 22:29:11 +00003013void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00003014{
Douglas Gregor319ac892009-04-23 22:29:11 +00003015 ObjCClassType = T;
3016
3017 const TypedefType *TT = T->getAsTypedefType();
3018 if (!TT)
3019 return;
3020 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00003021
3022 // typedef struct objc_class *Class;
3023 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
3024 assert(ptr && "'Class' incorrectly typed");
3025 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
3026 assert(rec && "'Class' incorrectly typed");
3027 ClassStructType = rec;
3028}
3029
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003030void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3031 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003032 "'NSConstantString' type already set!");
3033
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003034 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003035}
3036
Douglas Gregor7532dc62009-03-30 22:58:21 +00003037/// \brief Retrieve the template name that represents a qualified
3038/// template name such as \c std::vector.
3039TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3040 bool TemplateKeyword,
3041 TemplateDecl *Template) {
3042 llvm::FoldingSetNodeID ID;
3043 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3044
3045 void *InsertPos = 0;
3046 QualifiedTemplateName *QTN =
3047 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3048 if (!QTN) {
3049 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3050 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3051 }
3052
3053 return TemplateName(QTN);
3054}
3055
3056/// \brief Retrieve the template name that represents a dependent
3057/// template name such as \c MetaFun::template apply.
3058TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3059 const IdentifierInfo *Name) {
3060 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3061
3062 llvm::FoldingSetNodeID ID;
3063 DependentTemplateName::Profile(ID, NNS, Name);
3064
3065 void *InsertPos = 0;
3066 DependentTemplateName *QTN =
3067 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3068
3069 if (QTN)
3070 return TemplateName(QTN);
3071
3072 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3073 if (CanonNNS == NNS) {
3074 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3075 } else {
3076 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3077 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3078 }
3079
3080 DependentTemplateNames.InsertNode(QTN, InsertPos);
3081 return TemplateName(QTN);
3082}
3083
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003084/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003085/// TargetInfo, produce the corresponding type. The unsigned @p Type
3086/// is actually a value of type @c TargetInfo::IntType.
3087QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003088 switch (Type) {
3089 case TargetInfo::NoInt: return QualType();
3090 case TargetInfo::SignedShort: return ShortTy;
3091 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3092 case TargetInfo::SignedInt: return IntTy;
3093 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3094 case TargetInfo::SignedLong: return LongTy;
3095 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3096 case TargetInfo::SignedLongLong: return LongLongTy;
3097 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3098 }
3099
3100 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003101 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003102}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003103
3104//===----------------------------------------------------------------------===//
3105// Type Predicates.
3106//===----------------------------------------------------------------------===//
3107
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003108/// isObjCNSObjectType - Return true if this is an NSObject object using
3109/// NSObject attribute on a c-style pointer type.
3110/// FIXME - Make it work directly on types.
3111///
3112bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3113 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3114 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003115 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003116 return true;
3117 }
3118 return false;
3119}
3120
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003121/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3122/// to an object type. This includes "id" and "Class" (two 'special' pointers
3123/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3124/// ID type).
3125bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00003126 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003127 return true;
3128
Steve Naroff6ae98502008-10-21 18:24:04 +00003129 // Blocks are objects.
3130 if (Ty->isBlockPointerType())
3131 return true;
3132
3133 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00003134 const PointerType *PT = Ty->getAsPointerType();
3135 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003136 return false;
3137
Chris Lattner16ede0e2009-04-12 23:51:02 +00003138 // If this a pointer to an interface (e.g. NSString*), it is ok.
3139 if (PT->getPointeeType()->isObjCInterfaceType() ||
3140 // If is has NSObject attribute, OK as well.
3141 isObjCNSObjectType(Ty))
3142 return true;
3143
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003144 // Check to see if this is 'id' or 'Class', both of which are typedefs for
3145 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00003146 // underlying type. Iteratively strip off typedefs so that we can handle
3147 // typedefs of typedefs.
3148 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3149 if (Ty.getUnqualifiedType() == getObjCIdType() ||
3150 Ty.getUnqualifiedType() == getObjCClassType())
3151 return true;
3152
3153 Ty = TDT->getDecl()->getUnderlyingType();
3154 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003155
Chris Lattner16ede0e2009-04-12 23:51:02 +00003156 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003157}
3158
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003159/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3160/// garbage collection attribute.
3161///
3162QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003163 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003164 if (getLangOptions().ObjC1 &&
3165 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003166 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003167 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003168 // (or pointers to them) be treated as though they were declared
3169 // as __strong.
3170 if (GCAttrs == QualType::GCNone) {
3171 if (isObjCObjectPointerType(Ty))
3172 GCAttrs = QualType::Strong;
3173 else if (Ty->isPointerType())
3174 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3175 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003176 // Non-pointers have none gc'able attribute regardless of the attribute
3177 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003178 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003179 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003180 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003181 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003182}
3183
Chris Lattner6ac46a42008-04-07 06:51:04 +00003184//===----------------------------------------------------------------------===//
3185// Type Compatibility Testing
3186//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003187
Chris Lattner6ac46a42008-04-07 06:51:04 +00003188/// areCompatVectorTypes - Return true if the two specified vector types are
3189/// compatible.
3190static bool areCompatVectorTypes(const VectorType *LHS,
3191 const VectorType *RHS) {
3192 assert(LHS->isCanonical() && RHS->isCanonical());
3193 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003194 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003195}
3196
Eli Friedman3d815e72008-08-22 00:56:42 +00003197/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003198/// compatible for assignment from RHS to LHS. This handles validation of any
3199/// protocol qualifiers on the LHS or RHS.
3200///
Eli Friedman3d815e72008-08-22 00:56:42 +00003201bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3202 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003203 // Verify that the base decls are compatible: the RHS must be a subclass of
3204 // the LHS.
3205 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3206 return false;
3207
3208 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3209 // protocol qualified at all, then we are good.
3210 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3211 return true;
3212
3213 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3214 // isn't a superset.
3215 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3216 return true; // FIXME: should return false!
3217
3218 // Finally, we must have two protocol-qualified interfaces.
3219 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3220 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003221
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003222 // All LHS protocols must have a presence on the RHS.
3223 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003224
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003225 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3226 LHSPE = LHSP->qual_end();
3227 LHSPI != LHSPE; LHSPI++) {
3228 bool RHSImplementsProtocol = false;
3229
3230 // If the RHS doesn't implement the protocol on the left, the types
3231 // are incompatible.
3232 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3233 RHSPE = RHSP->qual_end();
3234 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3235 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3236 RHSImplementsProtocol = true;
3237 }
3238 // FIXME: For better diagnostics, consider passing back the protocol name.
3239 if (!RHSImplementsProtocol)
3240 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003241 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003242 // The RHS implements all protocols listed on the LHS.
3243 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003244}
3245
Steve Naroff389bf462009-02-12 17:52:19 +00003246bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3247 // get the "pointed to" types
3248 const PointerType *LHSPT = LHS->getAsPointerType();
3249 const PointerType *RHSPT = RHS->getAsPointerType();
3250
3251 if (!LHSPT || !RHSPT)
3252 return false;
3253
3254 QualType lhptee = LHSPT->getPointeeType();
3255 QualType rhptee = RHSPT->getPointeeType();
3256 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
3257 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
3258 // ID acts sort of like void* for ObjC interfaces
3259 if (LHSIface && isObjCIdStructType(rhptee))
3260 return true;
3261 if (RHSIface && isObjCIdStructType(lhptee))
3262 return true;
3263 if (!LHSIface || !RHSIface)
3264 return false;
3265 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
3266 canAssignObjCInterfaces(RHSIface, LHSIface);
3267}
3268
Steve Naroffec0550f2007-10-15 20:41:53 +00003269/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3270/// both shall have the identically qualified version of a compatible type.
3271/// C99 6.2.7p1: Two types have compatible types if their types are the
3272/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003273bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3274 return !mergeTypes(LHS, RHS).isNull();
3275}
3276
3277QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3278 const FunctionType *lbase = lhs->getAsFunctionType();
3279 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003280 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3281 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003282 bool allLTypes = true;
3283 bool allRTypes = true;
3284
3285 // Check return type
3286 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3287 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003288 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3289 allLTypes = false;
3290 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3291 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003292
3293 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003294 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3295 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003296 unsigned lproto_nargs = lproto->getNumArgs();
3297 unsigned rproto_nargs = rproto->getNumArgs();
3298
3299 // Compatible functions must have the same number of arguments
3300 if (lproto_nargs != rproto_nargs)
3301 return QualType();
3302
3303 // Variadic and non-variadic functions aren't compatible
3304 if (lproto->isVariadic() != rproto->isVariadic())
3305 return QualType();
3306
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003307 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3308 return QualType();
3309
Eli Friedman3d815e72008-08-22 00:56:42 +00003310 // Check argument compatibility
3311 llvm::SmallVector<QualType, 10> types;
3312 for (unsigned i = 0; i < lproto_nargs; i++) {
3313 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3314 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3315 QualType argtype = mergeTypes(largtype, rargtype);
3316 if (argtype.isNull()) return QualType();
3317 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003318 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3319 allLTypes = false;
3320 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3321 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003322 }
3323 if (allLTypes) return lhs;
3324 if (allRTypes) return rhs;
3325 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003326 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003327 }
3328
3329 if (lproto) allRTypes = false;
3330 if (rproto) allLTypes = false;
3331
Douglas Gregor72564e72009-02-26 23:50:07 +00003332 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003333 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003334 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003335 if (proto->isVariadic()) return QualType();
3336 // Check that the types are compatible with the types that
3337 // would result from default argument promotions (C99 6.7.5.3p15).
3338 // The only types actually affected are promotable integer
3339 // types and floats, which would be passed as a different
3340 // type depending on whether the prototype is visible.
3341 unsigned proto_nargs = proto->getNumArgs();
3342 for (unsigned i = 0; i < proto_nargs; ++i) {
3343 QualType argTy = proto->getArgType(i);
3344 if (argTy->isPromotableIntegerType() ||
3345 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3346 return QualType();
3347 }
3348
3349 if (allLTypes) return lhs;
3350 if (allRTypes) return rhs;
3351 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003352 proto->getNumArgs(), lproto->isVariadic(),
3353 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003354 }
3355
3356 if (allLTypes) return lhs;
3357 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003358 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003359}
3360
3361QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003362 // C++ [expr]: If an expression initially has the type "reference to T", the
3363 // type is adjusted to "T" prior to any further analysis, the expression
3364 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003365 // expression is an lvalue unless the reference is an rvalue reference and
3366 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003367 // FIXME: C++ shouldn't be going through here! The rules are different
3368 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003369 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3370 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003371 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003372 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003373 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003374 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003375
Eli Friedman3d815e72008-08-22 00:56:42 +00003376 QualType LHSCan = getCanonicalType(LHS),
3377 RHSCan = getCanonicalType(RHS);
3378
3379 // If two types are identical, they are compatible.
3380 if (LHSCan == RHSCan)
3381 return LHS;
3382
3383 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003384 // Note that we handle extended qualifiers later, in the
3385 // case for ExtQualType.
3386 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003387 return QualType();
3388
Eli Friedman852d63b2009-06-01 01:22:52 +00003389 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3390 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003391
Chris Lattner1adb8832008-01-14 05:45:46 +00003392 // We want to consider the two function types to be the same for these
3393 // comparisons, just force one to the other.
3394 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3395 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003396
Eli Friedman07d25872009-06-02 05:28:56 +00003397 // Strip off objc_gc attributes off the top level so they can be merged.
3398 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003399 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003400 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3401 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003402 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003403 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003404 // __strong attribue is redundant if other decl is an objective-c
3405 // object pointer (or decorated with __strong attribute); otherwise
3406 // issue error.
3407 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3408 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3409 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3410 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003411 return QualType();
3412
Eli Friedman07d25872009-06-02 05:28:56 +00003413 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3414 RHS.getCVRQualifiers());
3415 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003416 if (!Result.isNull()) {
3417 if (Result.getObjCGCAttr() == QualType::GCNone)
3418 Result = getObjCGCQualType(Result, GCAttr);
3419 else if (Result.getObjCGCAttr() != GCAttr)
3420 Result = QualType();
3421 }
Eli Friedman07d25872009-06-02 05:28:56 +00003422 return Result;
3423 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003424 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003425 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003426 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3427 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003428 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3429 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003430 // __strong attribue is redundant if other decl is an objective-c
3431 // object pointer (or decorated with __strong attribute); otherwise
3432 // issue error.
3433 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3434 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3435 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3436 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003437 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003438
Eli Friedman07d25872009-06-02 05:28:56 +00003439 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3440 LHS.getCVRQualifiers());
3441 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003442 if (!Result.isNull()) {
3443 if (Result.getObjCGCAttr() == QualType::GCNone)
3444 Result = getObjCGCQualType(Result, GCAttr);
3445 else if (Result.getObjCGCAttr() != GCAttr)
3446 Result = QualType();
3447 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003448 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003449 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003450 }
3451
Eli Friedman4c721d32008-02-12 08:23:06 +00003452 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003453 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3454 LHSClass = Type::ConstantArray;
3455 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3456 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003457
Nate Begeman213541a2008-04-18 23:10:10 +00003458 // Canonicalize ExtVector -> Vector.
3459 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3460 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003461
Chris Lattnerb0489812008-04-07 06:38:24 +00003462 // Consider qualified interfaces and interfaces the same.
3463 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3464 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003465
Chris Lattnera36a61f2008-04-07 05:43:21 +00003466 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003467 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003468 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3469 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003470
Steve Naroffd824c9c2009-04-14 15:11:46 +00003471 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3472 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003473 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003474 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003475 return RHS;
3476
Steve Naroffbc76dd02008-12-10 22:14:21 +00003477 // ID is compatible with all qualified id types.
3478 if (LHS->isObjCQualifiedIdType()) {
3479 if (const PointerType *PT = RHS->getAsPointerType()) {
3480 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003481 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003482 return LHS;
3483 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3484 // Unfortunately, this API is part of Sema (which we don't have access
3485 // to. Need to refactor. The following check is insufficient, since we
3486 // need to make sure the class implements the protocol.
3487 if (pType->isObjCInterfaceType())
3488 return LHS;
3489 }
3490 }
3491 if (RHS->isObjCQualifiedIdType()) {
3492 if (const PointerType *PT = LHS->getAsPointerType()) {
3493 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003494 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003495 return RHS;
3496 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3497 // Unfortunately, this API is part of Sema (which we don't have access
3498 // to. Need to refactor. The following check is insufficient, since we
3499 // need to make sure the class implements the protocol.
3500 if (pType->isObjCInterfaceType())
3501 return RHS;
3502 }
3503 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003504 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3505 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003506 if (const EnumType* ETy = LHS->getAsEnumType()) {
3507 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3508 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003509 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003510 if (const EnumType* ETy = RHS->getAsEnumType()) {
3511 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3512 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003513 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003514
Eli Friedman3d815e72008-08-22 00:56:42 +00003515 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003516 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003517
Steve Naroff4a746782008-01-09 22:43:08 +00003518 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003519 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003520#define TYPE(Class, Base)
3521#define ABSTRACT_TYPE(Class, Base)
3522#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3523#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3524#include "clang/AST/TypeNodes.def"
3525 assert(false && "Non-canonical and dependent types shouldn't get here");
3526 return QualType();
3527
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003528 case Type::LValueReference:
3529 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003530 case Type::MemberPointer:
3531 assert(false && "C++ should never be in mergeTypes");
3532 return QualType();
3533
3534 case Type::IncompleteArray:
3535 case Type::VariableArray:
3536 case Type::FunctionProto:
3537 case Type::ExtVector:
3538 case Type::ObjCQualifiedInterface:
3539 assert(false && "Types are eliminated above");
3540 return QualType();
3541
Chris Lattner1adb8832008-01-14 05:45:46 +00003542 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003543 {
3544 // Merge two pointer types, while trying to preserve typedef info
3545 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3546 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3547 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3548 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003549 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003550 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003551 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003552 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003553 return getPointerType(ResultType);
3554 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003555 case Type::BlockPointer:
3556 {
3557 // Merge two block pointer types, while trying to preserve typedef info
3558 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3559 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3560 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3561 if (ResultType.isNull()) return QualType();
3562 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3563 return LHS;
3564 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3565 return RHS;
3566 return getBlockPointerType(ResultType);
3567 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003568 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003569 {
3570 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3571 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3572 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3573 return QualType();
3574
3575 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3576 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3577 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3578 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003579 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3580 return LHS;
3581 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3582 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003583 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3584 ArrayType::ArraySizeModifier(), 0);
3585 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3586 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003587 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3588 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003589 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3590 return LHS;
3591 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3592 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003593 if (LVAT) {
3594 // FIXME: This isn't correct! But tricky to implement because
3595 // the array's size has to be the size of LHS, but the type
3596 // has to be different.
3597 return LHS;
3598 }
3599 if (RVAT) {
3600 // FIXME: This isn't correct! But tricky to implement because
3601 // the array's size has to be the size of RHS, but the type
3602 // has to be different.
3603 return RHS;
3604 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003605 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3606 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003607 return getIncompleteArrayType(ResultType,
3608 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003609 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003610 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003611 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003612 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003613 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003614 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003615 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3616 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003617 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003618 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003619 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003620 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003621 case Type::Complex:
3622 // Distinct complex types are incompatible.
3623 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003624 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003625 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003626 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3627 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003628 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003629 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003630 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003631 // FIXME: This should be type compatibility, e.g. whether
3632 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003633 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3634 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3635 if (LHSIface && RHSIface &&
3636 canAssignObjCInterfaces(LHSIface, RHSIface))
3637 return LHS;
3638
Eli Friedman3d815e72008-08-22 00:56:42 +00003639 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003640 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003641 case Type::ObjCObjectPointer:
3642 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003643 // Distinct qualified id's are not compatible.
3644 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003645 case Type::FixedWidthInt:
3646 // Distinct fixed-width integers are not compatible.
3647 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003648 case Type::ExtQual:
3649 // FIXME: ExtQual types can be compatible even if they're not
3650 // identical!
3651 return QualType();
3652 // First attempt at an implementation, but I'm not really sure it's
3653 // right...
3654#if 0
3655 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3656 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3657 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3658 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3659 return QualType();
3660 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3661 LHSBase = QualType(LQual->getBaseType(), 0);
3662 RHSBase = QualType(RQual->getBaseType(), 0);
3663 ResultType = mergeTypes(LHSBase, RHSBase);
3664 if (ResultType.isNull()) return QualType();
3665 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3666 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3667 return LHS;
3668 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3669 return RHS;
3670 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3671 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3672 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3673 return ResultType;
3674#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003675
3676 case Type::TemplateSpecialization:
3677 assert(false && "Dependent types have no size");
3678 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003679 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003680
3681 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003682}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003683
Chris Lattner5426bf62008-04-07 07:01:58 +00003684//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003685// Integer Predicates
3686//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003687
Eli Friedmanad74a752008-06-28 06:23:08 +00003688unsigned ASTContext::getIntWidth(QualType T) {
3689 if (T == BoolTy)
3690 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003691 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3692 return FWIT->getWidth();
3693 }
3694 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003695 return (unsigned)getTypeSize(T);
3696}
3697
3698QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3699 assert(T->isSignedIntegerType() && "Unexpected type");
3700 if (const EnumType* ETy = T->getAsEnumType())
3701 T = ETy->getDecl()->getIntegerType();
3702 const BuiltinType* BTy = T->getAsBuiltinType();
3703 assert (BTy && "Unexpected signed integer type");
3704 switch (BTy->getKind()) {
3705 case BuiltinType::Char_S:
3706 case BuiltinType::SChar:
3707 return UnsignedCharTy;
3708 case BuiltinType::Short:
3709 return UnsignedShortTy;
3710 case BuiltinType::Int:
3711 return UnsignedIntTy;
3712 case BuiltinType::Long:
3713 return UnsignedLongTy;
3714 case BuiltinType::LongLong:
3715 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003716 case BuiltinType::Int128:
3717 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003718 default:
3719 assert(0 && "Unexpected signed integer type");
3720 return QualType();
3721 }
3722}
3723
Douglas Gregor2cf26342009-04-09 22:27:44 +00003724ExternalASTSource::~ExternalASTSource() { }
3725
3726void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003727
3728
3729//===----------------------------------------------------------------------===//
3730// Builtin Type Computation
3731//===----------------------------------------------------------------------===//
3732
3733/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3734/// pointer over the consumed characters. This returns the resultant type.
3735static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3736 ASTContext::GetBuiltinTypeError &Error,
3737 bool AllowTypeModifiers = true) {
3738 // Modifiers.
3739 int HowLong = 0;
3740 bool Signed = false, Unsigned = false;
3741
3742 // Read the modifiers first.
3743 bool Done = false;
3744 while (!Done) {
3745 switch (*Str++) {
3746 default: Done = true; --Str; break;
3747 case 'S':
3748 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3749 assert(!Signed && "Can't use 'S' modifier multiple times!");
3750 Signed = true;
3751 break;
3752 case 'U':
3753 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3754 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3755 Unsigned = true;
3756 break;
3757 case 'L':
3758 assert(HowLong <= 2 && "Can't have LLLL modifier");
3759 ++HowLong;
3760 break;
3761 }
3762 }
3763
3764 QualType Type;
3765
3766 // Read the base type.
3767 switch (*Str++) {
3768 default: assert(0 && "Unknown builtin type letter!");
3769 case 'v':
3770 assert(HowLong == 0 && !Signed && !Unsigned &&
3771 "Bad modifiers used with 'v'!");
3772 Type = Context.VoidTy;
3773 break;
3774 case 'f':
3775 assert(HowLong == 0 && !Signed && !Unsigned &&
3776 "Bad modifiers used with 'f'!");
3777 Type = Context.FloatTy;
3778 break;
3779 case 'd':
3780 assert(HowLong < 2 && !Signed && !Unsigned &&
3781 "Bad modifiers used with 'd'!");
3782 if (HowLong)
3783 Type = Context.LongDoubleTy;
3784 else
3785 Type = Context.DoubleTy;
3786 break;
3787 case 's':
3788 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3789 if (Unsigned)
3790 Type = Context.UnsignedShortTy;
3791 else
3792 Type = Context.ShortTy;
3793 break;
3794 case 'i':
3795 if (HowLong == 3)
3796 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3797 else if (HowLong == 2)
3798 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3799 else if (HowLong == 1)
3800 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3801 else
3802 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3803 break;
3804 case 'c':
3805 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3806 if (Signed)
3807 Type = Context.SignedCharTy;
3808 else if (Unsigned)
3809 Type = Context.UnsignedCharTy;
3810 else
3811 Type = Context.CharTy;
3812 break;
3813 case 'b': // boolean
3814 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3815 Type = Context.BoolTy;
3816 break;
3817 case 'z': // size_t.
3818 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3819 Type = Context.getSizeType();
3820 break;
3821 case 'F':
3822 Type = Context.getCFConstantStringType();
3823 break;
3824 case 'a':
3825 Type = Context.getBuiltinVaListType();
3826 assert(!Type.isNull() && "builtin va list type not initialized!");
3827 break;
3828 case 'A':
3829 // This is a "reference" to a va_list; however, what exactly
3830 // this means depends on how va_list is defined. There are two
3831 // different kinds of va_list: ones passed by value, and ones
3832 // passed by reference. An example of a by-value va_list is
3833 // x86, where va_list is a char*. An example of by-ref va_list
3834 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3835 // we want this argument to be a char*&; for x86-64, we want
3836 // it to be a __va_list_tag*.
3837 Type = Context.getBuiltinVaListType();
3838 assert(!Type.isNull() && "builtin va list type not initialized!");
3839 if (Type->isArrayType()) {
3840 Type = Context.getArrayDecayedType(Type);
3841 } else {
3842 Type = Context.getLValueReferenceType(Type);
3843 }
3844 break;
3845 case 'V': {
3846 char *End;
3847
3848 unsigned NumElements = strtoul(Str, &End, 10);
3849 assert(End != Str && "Missing vector size");
3850
3851 Str = End;
3852
3853 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3854 Type = Context.getVectorType(ElementType, NumElements);
3855 break;
3856 }
3857 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003858 Type = Context.getFILEType();
3859 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003860 Error = ASTContext::GE_Missing_FILE;
3861 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003862 } else {
3863 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003864 }
3865 }
3866 }
3867
3868 if (!AllowTypeModifiers)
3869 return Type;
3870
3871 Done = false;
3872 while (!Done) {
3873 switch (*Str++) {
3874 default: Done = true; --Str; break;
3875 case '*':
3876 Type = Context.getPointerType(Type);
3877 break;
3878 case '&':
3879 Type = Context.getLValueReferenceType(Type);
3880 break;
3881 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3882 case 'C':
3883 Type = Type.getQualifiedType(QualType::Const);
3884 break;
3885 }
3886 }
3887
3888 return Type;
3889}
3890
3891/// GetBuiltinType - Return the type for the specified builtin.
3892QualType ASTContext::GetBuiltinType(unsigned id,
3893 GetBuiltinTypeError &Error) {
3894 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3895
3896 llvm::SmallVector<QualType, 8> ArgTypes;
3897
3898 Error = GE_None;
3899 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3900 if (Error != GE_None)
3901 return QualType();
3902 while (TypeStr[0] && TypeStr[0] != '.') {
3903 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3904 if (Error != GE_None)
3905 return QualType();
3906
3907 // Do array -> pointer decay. The builtin should use the decayed type.
3908 if (Ty->isArrayType())
3909 Ty = getArrayDecayedType(Ty);
3910
3911 ArgTypes.push_back(Ty);
3912 }
3913
3914 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3915 "'.' should only occur at end of builtin type list!");
3916
3917 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3918 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3919 return getFunctionNoProtoType(ResType);
3920 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3921 TypeStr[0] == '.', 0);
3922}