blob: 7f5fa35842af279f368e24c728e989c588dc005c [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"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000025#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000027#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000028#include "RecordLayoutBuilder.h"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
32enum FloatingRank {
33 FloatRank, DoubleRank, LongDoubleRank
34};
35
Chris Lattner61710852008-10-05 17:34:18 +000036ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
37 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000038 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000039 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000040 bool FreeMem, unsigned size_reserve) :
41 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000042 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000043 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
44 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000045 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000046 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000047 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000048 ObjCIdRedefinitionType = QualType();
49 ObjCClassRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000050 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000051 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000052 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000053}
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055ASTContext::~ASTContext() {
56 // Deallocate all the types.
57 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000058 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000059 Types.pop_back();
60 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000061
Nuno Lopesb74668e2008-12-17 22:30:25 +000062 {
John McCall0953e762009-09-24 19:53:00 +000063 llvm::FoldingSet<ExtQuals>::iterator
64 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
65 while (I != E)
66 Deallocate(&*I++);
67 }
68
69 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
71 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
72 while (I != E) {
73 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
74 delete R;
75 }
76 }
77
78 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000079 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
80 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000081 while (I != E) {
82 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
83 delete R;
84 }
85 }
86
Douglas Gregorab452ba2009-03-26 23:50:42 +000087 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000088 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
89 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000090 NNSEnd = NestedNameSpecifiers.end();
91 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000092 /* Increment in loop */)
93 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000094
95 if (GlobalNestedNameSpecifier)
96 GlobalNestedNameSpecifier->Destroy(*this);
97
Eli Friedmanb26153c2008-05-27 03:08:09 +000098 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000099}
100
Mike Stump1eb44332009-09-09 15:08:12 +0000101void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000102ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
103 ExternalSource.reset(Source.take());
104}
105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106void ASTContext::PrintStats() const {
107 fprintf(stderr, "*** AST Context Stats:\n");
108 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000109
Douglas Gregordbe833d2009-05-26 14:40:08 +0000110 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000111#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112#define ABSTRACT_TYPE(Name, Parent)
113#include "clang/AST/TypeNodes.def"
114 0 // Extra
115 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000116
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
118 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000119 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 }
121
Douglas Gregordbe833d2009-05-26 14:40:08 +0000122 unsigned Idx = 0;
123 unsigned TotalBytes = 0;
124#define TYPE(Name, Parent) \
125 if (counts[Idx]) \
126 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
127 TotalBytes += counts[Idx] * sizeof(Name##Type); \
128 ++Idx;
129#define ABSTRACT_TYPE(Name, Parent)
130#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Douglas Gregordbe833d2009-05-26 14:40:08 +0000132 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000133
134 if (ExternalSource.get()) {
135 fprintf(stderr, "\n");
136 ExternalSource->PrintStats();
137 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000138}
139
140
141void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000142 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
143 R = QualType(Ty, 0);
144 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000145}
146
Reid Spencer5f016e22007-07-11 17:01:13 +0000147void ASTContext::InitBuiltinTypes() {
148 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 // C99 6.2.5p19.
151 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // C99 6.2.5p2.
154 InitBuiltinType(BoolTy, BuiltinType::Bool);
155 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000156 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 InitBuiltinType(CharTy, BuiltinType::Char_S);
158 else
159 InitBuiltinType(CharTy, BuiltinType::Char_U);
160 // C99 6.2.5p4.
161 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
162 InitBuiltinType(ShortTy, BuiltinType::Short);
163 InitBuiltinType(IntTy, BuiltinType::Int);
164 InitBuiltinType(LongTy, BuiltinType::Long);
165 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 // C99 6.2.5p6.
168 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
169 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
170 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
171 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
172 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 // C99 6.2.5p10.
175 InitBuiltinType(FloatTy, BuiltinType::Float);
176 InitBuiltinType(DoubleTy, BuiltinType::Double);
177 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000178
Chris Lattner2df9ced2009-04-30 02:43:43 +0000179 // GNU extension, 128-bit integers.
180 InitBuiltinType(Int128Ty, BuiltinType::Int128);
181 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
182
Chris Lattner3a250322009-02-26 23:43:47 +0000183 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
184 InitBuiltinType(WCharTy, BuiltinType::WChar);
185 else // C99
186 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000187
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000188 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
189 InitBuiltinType(Char16Ty, BuiltinType::Char16);
190 else // C99
191 Char16Ty = getFromTargetType(Target.getChar16Type());
192
193 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
194 InitBuiltinType(Char32Ty, BuiltinType::Char32);
195 else // C99
196 Char32Ty = getFromTargetType(Target.getChar32Type());
197
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000198 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000199 InitBuiltinType(OverloadTy, BuiltinType::Overload);
200
201 // Placeholder type for type-dependent expressions whose type is
202 // completely unknown. No code should ever check a type against
203 // DependentTy and users should never see it; however, it is here to
204 // help diagnose failures to properly check for type-dependent
205 // expressions.
206 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000207
Mike Stump1eb44332009-09-09 15:08:12 +0000208 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000209 // not yet been deduced.
210 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // C99 6.2.5p11.
213 FloatComplexTy = getComplexType(FloatTy);
214 DoubleComplexTy = getComplexType(DoubleTy);
215 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000216
Steve Naroff7e219e42007-10-15 14:41:52 +0000217 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Steve Naroffde2e22d2009-07-15 18:40:39 +0000219 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
220 ObjCIdTypedefType = QualType();
221 ObjCClassTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Steve Naroffde2e22d2009-07-15 18:40:39 +0000223 // Builtin types for 'id' and 'Class'.
224 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
225 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000229 // void * type
230 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000231
232 // nullptr type (C++0x 2.14.7)
233 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000234}
235
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000236MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000237ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000238 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000239 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000240 = InstantiatedFromStaticDataMember.find(Var);
241 if (Pos == InstantiatedFromStaticDataMember.end())
242 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 return Pos->second;
245}
246
Mike Stump1eb44332009-09-09 15:08:12 +0000247void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000248ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
249 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000250 assert(Inst->isStaticDataMember() && "Not a static data member");
251 assert(Tmpl->isStaticDataMember() && "Not a static data member");
252 assert(!InstantiatedFromStaticDataMember[Inst] &&
253 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000254 InstantiatedFromStaticDataMember[Inst]
255 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000256}
257
Anders Carlsson0d8df782009-08-29 19:37:28 +0000258UnresolvedUsingDecl *
259ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
Mike Stump1eb44332009-09-09 15:08:12 +0000260 llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::iterator Pos
Anders Carlsson0d8df782009-08-29 19:37:28 +0000261 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
262 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
263 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Anders Carlsson0d8df782009-08-29 19:37:28 +0000265 return Pos->second;
266}
267
268void
269ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
270 UnresolvedUsingDecl *UUD) {
271 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
272 "Already noted what using decl what instantiated from");
273 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
274}
275
Anders Carlssond8b285f2009-09-01 04:26:58 +0000276FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
277 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
278 = InstantiatedFromUnnamedFieldDecl.find(Field);
279 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
280 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Anders Carlssond8b285f2009-09-01 04:26:58 +0000282 return Pos->second;
283}
284
285void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
286 FieldDecl *Tmpl) {
287 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
288 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
289 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
290 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Anders Carlssond8b285f2009-09-01 04:26:58 +0000292 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
293}
294
Douglas Gregor2e222532009-07-02 17:08:52 +0000295namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000296 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000297 : std::binary_function<SourceRange, SourceRange, bool> {
298 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Douglas Gregor2e222532009-07-02 17:08:52 +0000300 public:
301 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Douglas Gregor2e222532009-07-02 17:08:52 +0000303 bool operator()(SourceRange X, SourceRange Y) {
304 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
305 }
306 };
307}
308
309/// \brief Determine whether the given comment is a Doxygen-style comment.
310///
311/// \param Start the start of the comment text.
312///
313/// \param End the end of the comment text.
314///
315/// \param Member whether we want to check whether this is a member comment
316/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
317/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000318static bool
319isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000321 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000322 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
323 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
324 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 if (End - Start < 4)
327 return false;
328
329 assert(Start[0] == '/' && "Not a comment?");
330 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
331 return false;
332 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
333 return false;
334
335 return (Start[3] == '<') == Member;
336}
337
338/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000340const char *ASTContext::getCommentForDecl(const Decl *D) {
341 if (!D)
342 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Douglas Gregor2e222532009-07-02 17:08:52 +0000344 // Check whether we have cached a comment string for this declaration
345 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000346 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000347 = DeclComments.find(D);
348 if (Pos != DeclComments.end())
349 return Pos->second.c_str();
350
Mike Stump1eb44332009-09-09 15:08:12 +0000351 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000352 // that source, do so now.
353 if (ExternalSource && !LoadedExternalComments) {
354 std::vector<SourceRange> LoadedComments;
355 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregor2e222532009-07-02 17:08:52 +0000357 if (!LoadedComments.empty())
358 Comments.insert(Comments.begin(), LoadedComments.begin(),
359 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor2e222532009-07-02 17:08:52 +0000361 LoadedExternalComments = true;
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
364 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000365 if (Comments.empty())
366 return 0;
367
368 // If the declaration doesn't map directly to a location in a file, we
369 // can't find the comment.
370 SourceLocation DeclStartLoc = D->getLocStart();
371 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
372 return 0;
373
374 // Find the comment that occurs just before this declaration.
375 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000376 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000377 SourceRange(DeclStartLoc),
378 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 // Decompose the location for the start of the declaration and find the
381 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000382 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000383 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000384 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000385 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor2e222532009-07-02 17:08:52 +0000387 // First check whether we have a comment for a member.
388 if (LastComment != Comments.end() &&
389 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
390 isDoxygenComment(SourceMgr, *LastComment, true)) {
391 std::pair<FileID, unsigned> LastCommentEndDecomp
392 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
393 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
394 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000395 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000396 LastCommentEndDecomp.second)) {
397 // The Doxygen member comment comes after the declaration starts and
398 // is on the same line and in the same file as the declaration. This
399 // is the comment we want.
400 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000401 Result.append(FileBufferStart +
402 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 FileBufferStart + LastCommentEndDecomp.second + 1);
404 return Result.c_str();
405 }
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 if (LastComment == Comments.begin())
409 return 0;
410 --LastComment;
411
412 // Decompose the end of the comment.
413 std::pair<FileID, unsigned> LastCommentEndDecomp
414 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Douglas Gregor2e222532009-07-02 17:08:52 +0000416 // If the comment and the declaration aren't in the same file, then they
417 // aren't related.
418 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
419 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Douglas Gregor2e222532009-07-02 17:08:52 +0000421 // Check that we actually have a Doxygen comment.
422 if (!isDoxygenComment(SourceMgr, *LastComment))
423 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregor2e222532009-07-02 17:08:52 +0000425 // Compute the starting line for the declaration and for the end of the
426 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000427 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000428 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
429 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000430 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000431 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Douglas Gregor2e222532009-07-02 17:08:52 +0000433 // If the comment does not end on the line prior to the declaration, then
434 // the comment is not associated with the declaration at all.
435 if (CommentEndLine + 1 != DeclStartLine)
436 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Douglas Gregor2e222532009-07-02 17:08:52 +0000438 // We have a comment, but there may be more comments on the previous lines.
439 // Keep looking so long as the comments are still Doxygen comments and are
440 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000441 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000442 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
443 std::vector<SourceRange>::iterator FirstComment = LastComment;
444 while (FirstComment != Comments.begin()) {
445 // Look at the previous comment
446 --FirstComment;
447 std::pair<FileID, unsigned> Decomp
448 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor2e222532009-07-02 17:08:52 +0000450 // If this previous comment is in a different file, we're done.
451 if (Decomp.first != DeclStartDecomp.first) {
452 ++FirstComment;
453 break;
454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-07-02 17:08:52 +0000456 // If this comment is not a Doxygen comment, we're done.
457 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
458 ++FirstComment;
459 break;
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregor2e222532009-07-02 17:08:52 +0000462 // If the line number is not what we expected, we're done.
463 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
464 if (Line != ExpectedLine) {
465 ++FirstComment;
466 break;
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregor2e222532009-07-02 17:08:52 +0000469 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000470 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000471 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Douglas Gregor2e222532009-07-02 17:08:52 +0000474 // The iterator range [FirstComment, LastComment] contains all of the
475 // BCPL comments that, together, are associated with this declaration.
476 // Form a single comment block string for this declaration that concatenates
477 // all of these comments.
478 std::string &Result = DeclComments[D];
479 while (FirstComment != LastComment) {
480 std::pair<FileID, unsigned> DecompStart
481 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
482 std::pair<FileID, unsigned> DecompEnd
483 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
484 Result.append(FileBufferStart + DecompStart.second,
485 FileBufferStart + DecompEnd.second + 1);
486 ++FirstComment;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregor2e222532009-07-02 17:08:52 +0000489 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000490 Result.append(FileBufferStart +
491 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 FileBufferStart + LastCommentEndDecomp.second + 1);
493 return Result.c_str();
494}
495
Chris Lattner464175b2007-07-18 17:52:12 +0000496//===----------------------------------------------------------------------===//
497// Type Sizing and Analysis
498//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000499
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000500/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
501/// scalar floating point type.
502const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000503 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000504 assert(BT && "Not a floating point type!");
505 switch (BT->getKind()) {
506 default: assert(0 && "Not a floating point type!");
507 case BuiltinType::Float: return Target.getFloatFormat();
508 case BuiltinType::Double: return Target.getDoubleFormat();
509 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
510 }
511}
512
Mike Stump196efbf2009-09-22 02:43:44 +0000513/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000514/// specified decl. Note that bitfields do not have a valid alignment, so
515/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000516unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000517 unsigned Align = Target.getCharWidth();
518
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000519 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000520 Align = std::max(Align, AA->getAlignment());
521
Chris Lattneraf707ab2009-01-24 21:53:27 +0000522 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
523 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000524 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000525 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000526 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000527 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
528 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000529 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
530 T = cast<ArrayType>(T)->getElementType();
531
532 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
533 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000534 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000535
536 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000538
Chris Lattnera7674d82007-07-13 22:13:22 +0000539/// getTypeSize - Return the size of the specified type, in bits. This method
540/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000541///
542/// FIXME: Pointers into different addr spaces could have different sizes and
543/// alignment requirements: getPointerInfo should take an AddrSpace, this
544/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000545std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000546ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000547 uint64_t Width=0;
548 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000549 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000550#define TYPE(Class, Base)
551#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000552#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000553#define DEPENDENT_TYPE(Class, Base) case Type::Class:
554#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000555 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000556 break;
557
Chris Lattner692233e2007-07-13 22:27:08 +0000558 case Type::FunctionNoProto:
559 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000560 // GCC extension: alignof(function) = 32 bits
561 Width = 0;
562 Align = 32;
563 break;
564
Douglas Gregor72564e72009-02-26 23:50:07 +0000565 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000566 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000567 Width = 0;
568 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
569 break;
570
Steve Narofffb22d962007-08-30 01:06:46 +0000571 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000572 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattner98be4942008-03-05 18:54:05 +0000574 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000575 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000576 Align = EltInfo.second;
577 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000578 }
Nate Begeman213541a2008-04-18 23:10:10 +0000579 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000580 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000581 const VectorType *VT = cast<VectorType>(T);
582 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
583 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000584 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000585 // If the alignment is not a power of 2, round up to the next power of 2.
586 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000587 if (VT->getNumElements() & (VT->getNumElements()-1)) {
588 Align = llvm::NextPowerOf2(Align);
589 Width = llvm::RoundUpToAlignment(Width, Align);
590 }
Chris Lattner030d8842007-07-19 22:06:24 +0000591 break;
592 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000593
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000594 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000595 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000596 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000597 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000598 // GCC extension: alignof(void) = 8 bits.
599 Width = 0;
600 Align = 8;
601 break;
602
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000603 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000604 Width = Target.getBoolWidth();
605 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000606 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000607 case BuiltinType::Char_S:
608 case BuiltinType::Char_U:
609 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000610 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000611 Width = Target.getCharWidth();
612 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000613 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000614 case BuiltinType::WChar:
615 Width = Target.getWCharWidth();
616 Align = Target.getWCharAlign();
617 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000618 case BuiltinType::Char16:
619 Width = Target.getChar16Width();
620 Align = Target.getChar16Align();
621 break;
622 case BuiltinType::Char32:
623 Width = Target.getChar32Width();
624 Align = Target.getChar32Align();
625 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000626 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000627 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000628 Width = Target.getShortWidth();
629 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000630 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000631 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000632 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000633 Width = Target.getIntWidth();
634 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000635 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000636 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000637 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000638 Width = Target.getLongWidth();
639 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000640 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000641 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000643 Width = Target.getLongLongWidth();
644 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000646 case BuiltinType::Int128:
647 case BuiltinType::UInt128:
648 Width = 128;
649 Align = 128; // int128_t is 128-bit aligned on all targets.
650 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000651 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000652 Width = Target.getFloatWidth();
653 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000654 break;
655 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000656 Width = Target.getDoubleWidth();
657 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
659 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000660 Width = Target.getLongDoubleWidth();
661 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000663 case BuiltinType::NullPtr:
664 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
665 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000666 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000667 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000668 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000669 case Type::FixedWidthInt:
670 // FIXME: This isn't precisely correct; the width/alignment should depend
671 // on the available types for the target
672 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000673 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000674 Align = Width;
675 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000676 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000677 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000678 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000680 case Type::BlockPointer: {
681 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
682 Width = Target.getPointerWidth(AS);
683 Align = Target.getPointerAlign(AS);
684 break;
685 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000686 case Type::Pointer: {
687 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000688 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000689 Align = Target.getPointerAlign(AS);
690 break;
691 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000692 case Type::LValueReference:
693 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000694 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000695 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000696 // FIXME: This is wrong for struct layout: a reference in a struct has
697 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000698 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000699 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000700 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
701 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
702 // If we ever want to support other ABIs this needs to be abstracted.
703
Sebastian Redlf30208a2009-01-24 21:16:55 +0000704 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000705 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000706 getTypeInfo(getPointerDiffType());
707 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000708 if (Pointee->isFunctionType())
709 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000710 Align = PtrDiffInfo.second;
711 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000712 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000713 case Type::Complex: {
714 // Complex types have the same alignment as their elements, but twice the
715 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000716 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000717 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000718 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000719 Align = EltInfo.second;
720 break;
721 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000722 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000723 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000724 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
725 Width = Layout.getSize();
726 Align = Layout.getAlignment();
727 break;
728 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000729 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000730 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000731 const TagType *TT = cast<TagType>(T);
732
733 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000734 Width = 1;
735 Align = 1;
736 break;
737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Daniel Dunbar1d751182008-11-08 05:48:37 +0000739 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000740 return getTypeInfo(ET->getDecl()->getIntegerType());
741
Daniel Dunbar1d751182008-11-08 05:48:37 +0000742 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000743 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
744 Width = Layout.getSize();
745 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000746 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000747 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000748
Chris Lattner9fcfe922009-10-22 05:17:15 +0000749 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000750 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
751 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000752
Chris Lattner9fcfe922009-10-22 05:17:15 +0000753 case Type::Elaborated:
754 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
755 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000756
Douglas Gregor18857642009-04-30 17:32:17 +0000757 case Type::Typedef: {
758 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000759 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000760 Align = Aligned->getAlignment();
761 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
762 } else
763 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000764 break;
Chris Lattner71763312008-04-06 22:05:18 +0000765 }
Douglas Gregor18857642009-04-30 17:32:17 +0000766
767 case Type::TypeOfExpr:
768 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
769 .getTypePtr());
770
771 case Type::TypeOf:
772 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
773
Anders Carlsson395b4752009-06-24 19:06:50 +0000774 case Type::Decltype:
775 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
776 .getTypePtr());
777
Douglas Gregor18857642009-04-30 17:32:17 +0000778 case Type::QualifiedName:
779 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Douglas Gregor18857642009-04-30 17:32:17 +0000781 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000782 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000783 "Cannot request the size of a dependent type");
784 // FIXME: this is likely to be wrong once we support template
785 // aliases, since a template alias could refer to a typedef that
786 // has an __aligned__ attribute on it.
787 return getTypeInfo(getCanonicalType(T));
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Chris Lattner464175b2007-07-18 17:52:12 +0000790 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000791 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000792}
793
Chris Lattner34ebde42009-01-27 18:08:34 +0000794/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
795/// type for the current target in bits. This can be different than the ABI
796/// alignment in cases where it is beneficial for performance to overalign
797/// a data type.
798unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
799 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000800
801 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000802 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000803 T = CT->getElementType().getTypePtr();
804 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
805 T->isSpecificBuiltinType(BuiltinType::LongLong))
806 return std::max(ABIAlign, (unsigned)getTypeSize(T));
807
Chris Lattner34ebde42009-01-27 18:08:34 +0000808 return ABIAlign;
809}
810
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000811static void CollectLocalObjCIvars(ASTContext *Ctx,
812 const ObjCInterfaceDecl *OI,
813 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000814 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
815 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000816 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000817 if (!IVDecl->isInvalidDecl())
818 Fields.push_back(cast<FieldDecl>(IVDecl));
819 }
820}
821
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000822void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
823 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
824 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
825 CollectObjCIvars(SuperClass, Fields);
826 CollectLocalObjCIvars(this, OI, Fields);
827}
828
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000829/// ShallowCollectObjCIvars -
830/// Collect all ivars, including those synthesized, in the current class.
831///
832void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
833 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
834 bool CollectSynthesized) {
835 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836 E = OI->ivar_end(); I != E; ++I) {
837 Ivars.push_back(*I);
838 }
839 if (CollectSynthesized)
840 CollectSynthesizedIvars(OI, Ivars);
841}
842
Fariborz Jahanian98200742009-05-12 18:14:29 +0000843void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
844 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000845 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
846 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000847 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
848 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Fariborz Jahanian98200742009-05-12 18:14:29 +0000850 // Also look into nested protocols.
851 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
852 E = PD->protocol_end(); P != E; ++P)
853 CollectProtocolSynthesizedIvars(*P, Ivars);
854}
855
856/// CollectSynthesizedIvars -
857/// This routine collect synthesized ivars for the designated class.
858///
859void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
860 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000861 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
862 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000863 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
864 Ivars.push_back(Ivar);
865 }
866 // Also look into interface's protocol list for properties declared
867 // in the protocol and whose ivars are synthesized.
868 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
869 PE = OI->protocol_end(); P != PE; ++P) {
870 ObjCProtocolDecl *PD = (*P);
871 CollectProtocolSynthesizedIvars(PD, Ivars);
872 }
873}
874
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000875unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
876 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000877 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
878 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000879 if ((*I)->getPropertyIvarDecl())
880 ++count;
881
882 // Also look into nested protocols.
883 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
884 E = PD->protocol_end(); P != E; ++P)
885 count += CountProtocolSynthesizedIvars(*P);
886 return count;
887}
888
Mike Stump1eb44332009-09-09 15:08:12 +0000889unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000890 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000891 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
892 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000893 if ((*I)->getPropertyIvarDecl())
894 ++count;
895 }
896 // Also look into interface's protocol list for properties declared
897 // in the protocol and whose ivars are synthesized.
898 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
899 PE = OI->protocol_end(); P != PE; ++P) {
900 ObjCProtocolDecl *PD = (*P);
901 count += CountProtocolSynthesizedIvars(PD);
902 }
903 return count;
904}
905
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000906/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
907ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
908 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
909 I = ObjCImpls.find(D);
910 if (I != ObjCImpls.end())
911 return cast<ObjCImplementationDecl>(I->second);
912 return 0;
913}
914/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
915ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
916 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
917 I = ObjCImpls.find(D);
918 if (I != ObjCImpls.end())
919 return cast<ObjCCategoryImplDecl>(I->second);
920 return 0;
921}
922
923/// \brief Set the implementation of ObjCInterfaceDecl.
924void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
925 ObjCImplementationDecl *ImplD) {
926 assert(IFaceD && ImplD && "Passed null params");
927 ObjCImpls[IFaceD] = ImplD;
928}
929/// \brief Set the implementation of ObjCCategoryDecl.
930void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
931 ObjCCategoryImplDecl *ImplD) {
932 assert(CatD && ImplD && "Passed null params");
933 ObjCImpls[CatD] = ImplD;
934}
935
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000936/// \brief Allocate an uninitialized DeclaratorInfo.
937///
938/// The caller should initialize the memory held by DeclaratorInfo using
939/// the TypeLoc wrappers.
940///
941/// \param T the type that will be the basis for type source info. This type
942/// should refer to how the declarator was written in source code, not to
943/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +0000944DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
945 unsigned DataSize) {
946 if (!DataSize)
947 DataSize = TypeLoc::getFullDataSizeForType(T);
948 else
949 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
950 "incorrect data size provided to CreateDeclaratorInfo!");
951
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000952 DeclaratorInfo *DInfo =
953 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
954 new (DInfo) DeclaratorInfo(T);
955 return DInfo;
956}
957
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000958/// getInterfaceLayoutImpl - Get or compute information about the
959/// layout of the given interface.
960///
961/// \param Impl - If given, also include the layout of the interface's
962/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000963const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000964ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
965 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000966 assert(!D->isForwardDecl() && "Invalid interface decl!");
967
Devang Patel44a3dde2008-06-04 21:54:36 +0000968 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +0000969 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000970 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
971 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
972 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000973
Daniel Dunbar453addb2009-05-03 11:16:44 +0000974 // Add in synthesized ivar count if laying out an implementation.
975 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000976 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000977 unsigned SynthCount = CountSynthesizedIvars(D);
978 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000979 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000980 // entry. Note we can't cache this because we simply free all
981 // entries later; however we shouldn't look up implementations
982 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000983 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000984 return getObjCLayout(D, 0);
985 }
986
Mike Stump1eb44332009-09-09 15:08:12 +0000987 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +0000988 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
989 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Devang Patel44a3dde2008-06-04 21:54:36 +0000991 return *NewEntry;
992}
993
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000994const ASTRecordLayout &
995ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
996 return getObjCLayout(D, 0);
997}
998
999const ASTRecordLayout &
1000ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1001 return getObjCLayout(D->getClassInterface(), D);
1002}
1003
Devang Patel88a981b2007-11-01 19:11:01 +00001004/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001005/// specified record (struct/union/class), which indicates its size and field
1006/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001007const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001008 D = D->getDefinition(*this);
1009 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001010
Chris Lattner464175b2007-07-18 17:52:12 +00001011 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001012 // Note that we can't save a reference to the entry because this function
1013 // is recursive.
1014 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001015 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001016
Mike Stump1eb44332009-09-09 15:08:12 +00001017 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001018 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001019 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner5d2a6302007-07-18 18:26:58 +00001021 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001022}
1023
Chris Lattnera7674d82007-07-13 22:13:22 +00001024//===----------------------------------------------------------------------===//
1025// Type creation/memoization methods
1026//===----------------------------------------------------------------------===//
1027
John McCall0953e762009-09-24 19:53:00 +00001028QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1029 unsigned Fast = Quals.getFastQualifiers();
1030 Quals.removeFastQualifiers();
1031
1032 // Check if we've already instantiated this type.
1033 llvm::FoldingSetNodeID ID;
1034 ExtQuals::Profile(ID, TypeNode, Quals);
1035 void *InsertPos = 0;
1036 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1037 assert(EQ->getQualifiers() == Quals);
1038 QualType T = QualType(EQ, Fast);
1039 return T;
1040 }
1041
John McCall6b304a02009-09-24 23:30:46 +00001042 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001043 ExtQualNodes.InsertNode(New, InsertPos);
1044 QualType T = QualType(New, Fast);
1045 return T;
1046}
1047
1048QualType ASTContext::getVolatileType(QualType T) {
1049 QualType CanT = getCanonicalType(T);
1050 if (CanT.isVolatileQualified()) return T;
1051
1052 QualifierCollector Quals;
1053 const Type *TypeNode = Quals.strip(T);
1054 Quals.addVolatile();
1055
1056 return getExtQualType(TypeNode, Quals);
1057}
1058
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001059QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001060 QualType CanT = getCanonicalType(T);
1061 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001062 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001063
John McCall0953e762009-09-24 19:53:00 +00001064 // If we are composing extended qualifiers together, merge together
1065 // into one ExtQuals node.
1066 QualifierCollector Quals;
1067 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
John McCall0953e762009-09-24 19:53:00 +00001069 // If this type already has an address space specified, it cannot get
1070 // another one.
1071 assert(!Quals.hasAddressSpace() &&
1072 "Type cannot be in multiple addr spaces!");
1073 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
John McCall0953e762009-09-24 19:53:00 +00001075 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001076}
1077
Chris Lattnerb7d25532009-02-18 22:53:11 +00001078QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001079 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001080 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001081 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001082 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001084 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001086 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001087 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1088 return getPointerType(ResultType);
1089 }
1090 }
Mike Stump1eb44332009-09-09 15:08:12 +00001091
John McCall0953e762009-09-24 19:53:00 +00001092 // If we are composing extended qualifiers together, merge together
1093 // into one ExtQuals node.
1094 QualifierCollector Quals;
1095 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
John McCall0953e762009-09-24 19:53:00 +00001097 // If this type already has an ObjCGC specified, it cannot get
1098 // another one.
1099 assert(!Quals.hasObjCGCAttr() &&
1100 "Type cannot have multiple ObjCGCs!");
1101 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCall0953e762009-09-24 19:53:00 +00001103 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001104}
Chris Lattnera7674d82007-07-13 22:13:22 +00001105
Mike Stump24556362009-07-25 21:26:53 +00001106QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001107 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001108 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001109 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001110 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001111 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001112 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001113 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001114 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001115 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001116 } else {
1117 assert (T->isFunctionType()
1118 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001120 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1121 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001122 } else {
1123 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1124 ResultType
1125 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1126 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1127 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1128 F->getNumExceptions(), F->exception_begin(), true);
1129 }
Mike Stump24556362009-07-25 21:26:53 +00001130 }
John McCall0953e762009-09-24 19:53:00 +00001131
1132 return getQualifiedType(ResultType, T.getQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001133}
1134
Reid Spencer5f016e22007-07-11 17:01:13 +00001135/// getComplexType - Return the uniqued reference to the type for a complex
1136/// number with the specified element type.
1137QualType ASTContext::getComplexType(QualType T) {
1138 // Unique pointers, to guarantee there is only one pointer of a particular
1139 // structure.
1140 llvm::FoldingSetNodeID ID;
1141 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 void *InsertPos = 0;
1144 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1145 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 // If the pointee type isn't canonical, this won't be a canonical type either,
1148 // so fill in the canonical type field.
1149 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001150 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001151 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 // Get the new insert position for the node we care about.
1154 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001155 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 }
John McCall6b304a02009-09-24 23:30:46 +00001157 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001158 Types.push_back(New);
1159 ComplexTypes.InsertNode(New, InsertPos);
1160 return QualType(New, 0);
1161}
1162
Eli Friedmanf98aba32009-02-13 02:31:07 +00001163QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1164 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1165 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1166 FixedWidthIntType *&Entry = Map[Width];
1167 if (!Entry)
1168 Entry = new FixedWidthIntType(Width, Signed);
1169 return QualType(Entry, 0);
1170}
Reid Spencer5f016e22007-07-11 17:01:13 +00001171
1172/// getPointerType - Return the uniqued reference to the type for a pointer to
1173/// the specified type.
1174QualType ASTContext::getPointerType(QualType T) {
1175 // Unique pointers, to guarantee there is only one pointer of a particular
1176 // structure.
1177 llvm::FoldingSetNodeID ID;
1178 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 void *InsertPos = 0;
1181 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1182 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 // If the pointee type isn't canonical, this won't be a canonical type either,
1185 // so fill in the canonical type field.
1186 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001187 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001188 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 // Get the new insert position for the node we care about.
1191 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001192 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 }
John McCall6b304a02009-09-24 23:30:46 +00001194 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 Types.push_back(New);
1196 PointerTypes.InsertNode(New, InsertPos);
1197 return QualType(New, 0);
1198}
1199
Mike Stump1eb44332009-09-09 15:08:12 +00001200/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001201/// a pointer to the specified block.
1202QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001203 assert(T->isFunctionType() && "block of function types only");
1204 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001205 // structure.
1206 llvm::FoldingSetNodeID ID;
1207 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Steve Naroff5618bd42008-08-27 16:04:49 +00001209 void *InsertPos = 0;
1210 if (BlockPointerType *PT =
1211 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1212 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
1214 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001215 // type either so fill in the canonical type field.
1216 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001217 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001218 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Steve Naroff5618bd42008-08-27 16:04:49 +00001220 // Get the new insert position for the node we care about.
1221 BlockPointerType *NewIP =
1222 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001223 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001224 }
John McCall6b304a02009-09-24 23:30:46 +00001225 BlockPointerType *New
1226 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001227 Types.push_back(New);
1228 BlockPointerTypes.InsertNode(New, InsertPos);
1229 return QualType(New, 0);
1230}
1231
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001232/// getLValueReferenceType - Return the uniqued reference to the type for an
1233/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001234QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 // Unique pointers, to guarantee there is only one pointer of a particular
1236 // structure.
1237 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001238 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001239
1240 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001241 if (LValueReferenceType *RT =
1242 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001244
John McCall54e14c42009-10-22 22:37:11 +00001245 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1246
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 // If the referencee type isn't canonical, this won't be a canonical type
1248 // either, so fill in the canonical type field.
1249 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001250 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1251 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1252 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001255 LValueReferenceType *NewIP =
1256 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001257 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 }
1259
John McCall6b304a02009-09-24 23:30:46 +00001260 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001261 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1262 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001264 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001265
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001266 return QualType(New, 0);
1267}
1268
1269/// getRValueReferenceType - Return the uniqued reference to the type for an
1270/// rvalue reference to the specified type.
1271QualType ASTContext::getRValueReferenceType(QualType T) {
1272 // Unique pointers, to guarantee there is only one pointer of a particular
1273 // structure.
1274 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001275 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001276
1277 void *InsertPos = 0;
1278 if (RValueReferenceType *RT =
1279 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1280 return QualType(RT, 0);
1281
John McCall54e14c42009-10-22 22:37:11 +00001282 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1283
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001284 // If the referencee type isn't canonical, this won't be a canonical type
1285 // either, so fill in the canonical type field.
1286 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001287 if (InnerRef || !T.isCanonical()) {
1288 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1289 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001290
1291 // Get the new insert position for the node we care about.
1292 RValueReferenceType *NewIP =
1293 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1294 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1295 }
1296
John McCall6b304a02009-09-24 23:30:46 +00001297 RValueReferenceType *New
1298 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001299 Types.push_back(New);
1300 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 return QualType(New, 0);
1302}
1303
Sebastian Redlf30208a2009-01-24 21:16:55 +00001304/// getMemberPointerType - Return the uniqued reference to the type for a
1305/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001306QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001307 // Unique pointers, to guarantee there is only one pointer of a particular
1308 // structure.
1309 llvm::FoldingSetNodeID ID;
1310 MemberPointerType::Profile(ID, T, Cls);
1311
1312 void *InsertPos = 0;
1313 if (MemberPointerType *PT =
1314 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1315 return QualType(PT, 0);
1316
1317 // If the pointee or class type isn't canonical, this won't be a canonical
1318 // type either, so fill in the canonical type field.
1319 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001320 if (!T.isCanonical()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001321 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1322
1323 // Get the new insert position for the node we care about.
1324 MemberPointerType *NewIP =
1325 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1326 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1327 }
John McCall6b304a02009-09-24 23:30:46 +00001328 MemberPointerType *New
1329 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001330 Types.push_back(New);
1331 MemberPointerTypes.InsertNode(New, InsertPos);
1332 return QualType(New, 0);
1333}
1334
Mike Stump1eb44332009-09-09 15:08:12 +00001335/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001336/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001337QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001338 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001339 ArrayType::ArraySizeModifier ASM,
1340 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001341 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1342 "Constant array of VLAs is illegal!");
1343
Chris Lattner38aeec72009-05-13 04:12:56 +00001344 // Convert the array size into a canonical width matching the pointer size for
1345 // the target.
1346 llvm::APInt ArySize(ArySizeIn);
1347 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001350 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001353 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001354 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 // If the element type isn't canonical, this won't be a canonical type either,
1358 // so fill in the canonical type field.
1359 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001360 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001361 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001362 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001364 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001365 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001366 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
John McCall6b304a02009-09-24 23:30:46 +00001369 ConstantArrayType *New = new(*this,TypeAlignment)
1370 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001371 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 Types.push_back(New);
1373 return QualType(New, 0);
1374}
1375
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001376/// getVariableArrayType - Returns a non-unique reference to the type for a
1377/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001378QualType ASTContext::getVariableArrayType(QualType EltTy,
1379 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001380 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001381 unsigned EltTypeQuals,
1382 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001383 // Since we don't unique expressions, it isn't possible to unique VLA's
1384 // that have an expression provided for their size.
1385
John McCall6b304a02009-09-24 23:30:46 +00001386 VariableArrayType *New = new(*this, TypeAlignment)
1387 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001388
1389 VariableArrayTypes.push_back(New);
1390 Types.push_back(New);
1391 return QualType(New, 0);
1392}
1393
Douglas Gregor898574e2008-12-05 23:32:09 +00001394/// getDependentSizedArrayType - Returns a non-unique reference to
1395/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001396/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001397QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1398 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001399 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001400 unsigned EltTypeQuals,
1401 SourceRange Brackets) {
Mike Stump1eb44332009-09-09 15:08:12 +00001402 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001403 "Size must be type- or value-dependent!");
1404
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001405 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001406 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001407 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001408
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001409 void *InsertPos = 0;
1410 DependentSizedArrayType *Canon
1411 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1412 DependentSizedArrayType *New;
1413 if (Canon) {
1414 // We already have a canonical version of this array type; use it as
1415 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001416 New = new (*this, TypeAlignment)
1417 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1418 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001419 } else {
1420 QualType CanonEltTy = getCanonicalType(EltTy);
1421 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001422 New = new (*this, TypeAlignment)
1423 DependentSizedArrayType(*this, EltTy, QualType(),
1424 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001425 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1426 } else {
1427 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1428 ASM, EltTypeQuals,
1429 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001430 New = new (*this, TypeAlignment)
1431 DependentSizedArrayType(*this, EltTy, Canon,
1432 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001433 }
1434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Douglas Gregor898574e2008-12-05 23:32:09 +00001436 Types.push_back(New);
1437 return QualType(New, 0);
1438}
1439
Eli Friedmanc5773c42008-02-15 18:16:39 +00001440QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1441 ArrayType::ArraySizeModifier ASM,
1442 unsigned EltTypeQuals) {
1443 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001444 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001445
1446 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001447 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001448 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1449 return QualType(ATP, 0);
1450
1451 // If the element type isn't canonical, this won't be a canonical type
1452 // either, so fill in the canonical type field.
1453 QualType Canonical;
1454
John McCall467b27b2009-10-22 20:10:53 +00001455 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001456 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001457 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001458
1459 // Get the new insert position for the node we care about.
1460 IncompleteArrayType *NewIP =
1461 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001462 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001463 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001464
John McCall6b304a02009-09-24 23:30:46 +00001465 IncompleteArrayType *New = new (*this, TypeAlignment)
1466 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001467
1468 IncompleteArrayTypes.InsertNode(New, InsertPos);
1469 Types.push_back(New);
1470 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001471}
1472
Steve Naroff73322922007-07-18 18:00:27 +00001473/// getVectorType - Return the unique reference to a vector type of
1474/// the specified element type and size. VectorType must be a built-in type.
1475QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Chris Lattnerf52ab252008-04-06 22:59:24 +00001478 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001479 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 // Check if we've already instantiated a vector of this type.
1482 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001483 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 void *InsertPos = 0;
1485 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1486 return QualType(VTP, 0);
1487
1488 // If the element type isn't canonical, this won't be a canonical type either,
1489 // so fill in the canonical type field.
1490 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001491 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001492 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 // Get the new insert position for the node we care about.
1495 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001496 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 }
John McCall6b304a02009-09-24 23:30:46 +00001498 VectorType *New = new (*this, TypeAlignment)
1499 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 VectorTypes.InsertNode(New, InsertPos);
1501 Types.push_back(New);
1502 return QualType(New, 0);
1503}
1504
Nate Begeman213541a2008-04-18 23:10:10 +00001505/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001506/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001507QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001508 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Chris Lattnerf52ab252008-04-06 22:59:24 +00001510 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001511 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Steve Naroff73322922007-07-18 18:00:27 +00001513 // Check if we've already instantiated a vector of this type.
1514 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001515 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001516 void *InsertPos = 0;
1517 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1518 return QualType(VTP, 0);
1519
1520 // If the element type isn't canonical, this won't be a canonical type either,
1521 // so fill in the canonical type field.
1522 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001523 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001524 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Steve Naroff73322922007-07-18 18:00:27 +00001526 // Get the new insert position for the node we care about.
1527 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001528 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001529 }
John McCall6b304a02009-09-24 23:30:46 +00001530 ExtVectorType *New = new (*this, TypeAlignment)
1531 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001532 VectorTypes.InsertNode(New, InsertPos);
1533 Types.push_back(New);
1534 return QualType(New, 0);
1535}
1536
Mike Stump1eb44332009-09-09 15:08:12 +00001537QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001538 Expr *SizeExpr,
1539 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001540 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001541 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001542 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001544 void *InsertPos = 0;
1545 DependentSizedExtVectorType *Canon
1546 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1547 DependentSizedExtVectorType *New;
1548 if (Canon) {
1549 // We already have a canonical version of this array type; use it as
1550 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001551 New = new (*this, TypeAlignment)
1552 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1553 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001554 } else {
1555 QualType CanonVecTy = getCanonicalType(vecType);
1556 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001557 New = new (*this, TypeAlignment)
1558 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1559 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001560 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1561 } else {
1562 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1563 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001564 New = new (*this, TypeAlignment)
1565 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001566 }
1567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001569 Types.push_back(New);
1570 return QualType(New, 0);
1571}
1572
Douglas Gregor72564e72009-02-26 23:50:07 +00001573/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001574///
Mike Stump24556362009-07-25 21:26:53 +00001575QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Unique functions, to guarantee there is only one function of a particular
1577 // structure.
1578 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001579 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001582 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001583 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001587 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001588 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001591 FunctionNoProtoType *NewIP =
1592 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001593 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
Mike Stump1eb44332009-09-09 15:08:12 +00001595
John McCall6b304a02009-09-24 23:30:46 +00001596 FunctionNoProtoType *New = new (*this, TypeAlignment)
1597 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001599 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 return QualType(New, 0);
1601}
1602
1603/// getFunctionType - Return a normal function type with a typed argument
1604/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001605QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001606 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001607 unsigned TypeQuals, bool hasExceptionSpec,
1608 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001609 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // Unique functions, to guarantee there is only one function of a particular
1611 // structure.
1612 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001613 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001614 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001615 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001616
1617 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001618 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001619 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001621
1622 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001623 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001625 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 isCanonical = false;
1627
1628 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001629 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 QualType Canonical;
1631 if (!isCanonical) {
1632 llvm::SmallVector<QualType, 16> CanonicalArgs;
1633 CanonicalArgs.reserve(NumArgs);
1634 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001635 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001636
Chris Lattnerf52ab252008-04-06 22:59:24 +00001637 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001638 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001639 isVariadic, TypeQuals, false,
1640 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001641
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001643 FunctionProtoType *NewIP =
1644 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001645 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001647
Douglas Gregor72564e72009-02-26 23:50:07 +00001648 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001649 // for two variable size arrays (for parameter and exception types) at the
1650 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001651 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001652 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1653 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001654 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001655 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001656 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001657 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001659 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 return QualType(FTP, 0);
1661}
1662
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001663/// getTypeDeclType - Return the unique reference to the type for the
1664/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001665QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001666 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001667 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001669 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001670 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001671 else if (isa<TemplateTypeParmDecl>(Decl)) {
1672 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001673 } else if (ObjCInterfaceDecl *ObjCInterface
1674 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001675 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001676
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001677 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001678 if (PrevDecl)
1679 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001680 else
John McCall6b304a02009-09-24 23:30:46 +00001681 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001682 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001683 if (PrevDecl)
1684 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001685 else
John McCall6b304a02009-09-24 23:30:46 +00001686 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001687 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001688 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001689
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001690 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001691 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001692}
1693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694/// getTypedefType - Return the unique reference to the type for the
1695/// specified typename decl.
1696QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1697 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Chris Lattnerf52ab252008-04-06 22:59:24 +00001699 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001700 Decl->TypeForDecl = new(*this, TypeAlignment)
1701 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 Types.push_back(Decl->TypeForDecl);
1703 return QualType(Decl->TypeForDecl, 0);
1704}
1705
John McCall49a832b2009-10-18 09:09:24 +00001706/// \brief Retrieve a substitution-result type.
1707QualType
1708ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1709 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001710 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001711 && "replacement types must always be canonical");
1712
1713 llvm::FoldingSetNodeID ID;
1714 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1715 void *InsertPos = 0;
1716 SubstTemplateTypeParmType *SubstParm
1717 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1718
1719 if (!SubstParm) {
1720 SubstParm = new (*this, TypeAlignment)
1721 SubstTemplateTypeParmType(Parm, Replacement);
1722 Types.push_back(SubstParm);
1723 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1724 }
1725
1726 return QualType(SubstParm, 0);
1727}
1728
Douglas Gregorfab9d672009-02-05 23:33:38 +00001729/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001730/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001731/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001732QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001733 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001734 IdentifierInfo *Name) {
1735 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001736 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001737 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001738 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001739 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1740
1741 if (TypeParm)
1742 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001744 if (Name) {
1745 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001746 TypeParm = new (*this, TypeAlignment)
1747 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001748 } else
John McCall6b304a02009-09-24 23:30:46 +00001749 TypeParm = new (*this, TypeAlignment)
1750 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001751
1752 Types.push_back(TypeParm);
1753 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1754
1755 return QualType(TypeParm, 0);
1756}
1757
Mike Stump1eb44332009-09-09 15:08:12 +00001758QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001759ASTContext::getTemplateSpecializationType(TemplateName Template,
1760 const TemplateArgument *Args,
1761 unsigned NumArgs,
1762 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001763 if (!Canon.isNull())
1764 Canon = getCanonicalType(Canon);
1765 else {
1766 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001767 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1768 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1769 CanonArgs.reserve(NumArgs);
1770 for (unsigned I = 0; I != NumArgs; ++I)
1771 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1772
1773 // Determine whether this canonical template specialization type already
1774 // exists.
1775 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001776 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001777 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001778
1779 void *InsertPos = 0;
1780 TemplateSpecializationType *Spec
1781 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregor1275ae02009-07-28 23:00:59 +00001783 if (!Spec) {
1784 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001785 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001786 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001787 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001788 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001789 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001790 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001791 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001792 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Douglas Gregorb88e8882009-07-30 17:40:51 +00001795 if (Canon.isNull())
1796 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001797 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001798 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001799 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001800
Douglas Gregor1275ae02009-07-28 23:00:59 +00001801 // Allocate the (non-canonical) template specialization type, but don't
1802 // try to unique it: these types typically have location information that
1803 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001804 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001805 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001806 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001807 TemplateSpecializationType *Spec
1808 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001809 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Douglas Gregor55f6b142009-02-09 18:46:07 +00001811 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001812 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001813}
1814
Mike Stump1eb44332009-09-09 15:08:12 +00001815QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001816ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001817 QualType NamedType) {
1818 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001819 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001820
1821 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001822 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001823 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1824 if (T)
1825 return QualType(T, 0);
1826
Mike Stump1eb44332009-09-09 15:08:12 +00001827 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001828 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001829 Types.push_back(T);
1830 QualifiedNameTypes.InsertNode(T, InsertPos);
1831 return QualType(T, 0);
1832}
1833
Mike Stump1eb44332009-09-09 15:08:12 +00001834QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001835 const IdentifierInfo *Name,
1836 QualType Canon) {
1837 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1838
1839 if (Canon.isNull()) {
1840 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1841 if (CanonNNS != NNS)
1842 Canon = getTypenameType(CanonNNS, Name);
1843 }
1844
1845 llvm::FoldingSetNodeID ID;
1846 TypenameType::Profile(ID, NNS, Name);
1847
1848 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001849 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001850 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1851 if (T)
1852 return QualType(T, 0);
1853
1854 T = new (*this) TypenameType(NNS, Name, Canon);
1855 Types.push_back(T);
1856 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001857 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001858}
1859
Mike Stump1eb44332009-09-09 15:08:12 +00001860QualType
1861ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001862 const TemplateSpecializationType *TemplateId,
1863 QualType Canon) {
1864 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1865
1866 if (Canon.isNull()) {
1867 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1868 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1869 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1870 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001871 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001872 assert(CanonTemplateId &&
1873 "Canonical type must also be a template specialization type");
1874 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1875 }
1876 }
1877
1878 llvm::FoldingSetNodeID ID;
1879 TypenameType::Profile(ID, NNS, TemplateId);
1880
1881 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001882 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001883 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1884 if (T)
1885 return QualType(T, 0);
1886
1887 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1888 Types.push_back(T);
1889 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001890 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001891}
1892
John McCall7da24312009-09-05 00:15:47 +00001893QualType
1894ASTContext::getElaboratedType(QualType UnderlyingType,
1895 ElaboratedType::TagKind Tag) {
1896 llvm::FoldingSetNodeID ID;
1897 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
John McCall7da24312009-09-05 00:15:47 +00001899 void *InsertPos = 0;
1900 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1901 if (T)
1902 return QualType(T, 0);
1903
1904 QualType Canon = getCanonicalType(UnderlyingType);
1905
1906 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1907 Types.push_back(T);
1908 ElaboratedTypes.InsertNode(T, InsertPos);
1909 return QualType(T, 0);
1910}
1911
Chris Lattner88cb27a2008-04-07 04:56:42 +00001912/// CmpProtocolNames - Comparison predicate for sorting protocols
1913/// alphabetically.
1914static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1915 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001916 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001917}
1918
John McCall54e14c42009-10-22 22:37:11 +00001919static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
1920 unsigned NumProtocols) {
1921 if (NumProtocols == 0) return true;
1922
1923 for (unsigned i = 1; i != NumProtocols; ++i)
1924 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1925 return false;
1926 return true;
1927}
1928
1929static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00001930 unsigned &NumProtocols) {
1931 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Chris Lattner88cb27a2008-04-07 04:56:42 +00001933 // Sort protocols, keyed by name.
1934 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1935
1936 // Remove duplicates.
1937 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1938 NumProtocols = ProtocolsEnd-Protocols;
1939}
1940
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001941/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1942/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001943QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00001944 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001945 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001946 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001947 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001948
1949 void *InsertPos = 0;
1950 if (ObjCObjectPointerType *QT =
1951 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1952 return QualType(QT, 0);
1953
John McCall54e14c42009-10-22 22:37:11 +00001954 // Sort the protocol list alphabetically to canonicalize it.
1955 QualType Canonical;
1956 if (!InterfaceT.isCanonical() ||
1957 !areSortedAndUniqued(Protocols, NumProtocols)) {
1958 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
1959 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
1960 unsigned UniqueCount = NumProtocols;
1961
1962 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
1963 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
1964
1965 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
1966 &Sorted[0], UniqueCount);
1967 } else {
1968 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
1969 Protocols, NumProtocols);
1970 }
1971
1972 // Regenerate InsertPos.
1973 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1974 }
1975
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001976 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00001977 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00001978 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001980 Types.push_back(QType);
1981 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1982 return QualType(QType, 0);
1983}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001984
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001985/// getObjCInterfaceType - Return the unique reference to the type for the
1986/// specified ObjC interface decl. The list of protocols is optional.
1987QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001988 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001989 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001990 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001992 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001993 if (ObjCInterfaceType *QT =
1994 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001995 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001996
John McCall54e14c42009-10-22 22:37:11 +00001997 // Sort the protocol list alphabetically to canonicalize it.
1998 QualType Canonical;
1999 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2000 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2001 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2002
2003 unsigned UniqueCount = NumProtocols;
2004 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2005
2006 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2007
2008 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2009 }
2010
John McCall6b304a02009-09-24 23:30:46 +00002011 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002012 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002013 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002014
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002015 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002016 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002017 return QualType(QType, 0);
2018}
2019
Douglas Gregor72564e72009-02-26 23:50:07 +00002020/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2021/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002022/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002023/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002024/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002025QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002026 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002027 if (tofExpr->isTypeDependent()) {
2028 llvm::FoldingSetNodeID ID;
2029 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Douglas Gregorb1975722009-07-30 23:18:24 +00002031 void *InsertPos = 0;
2032 DependentTypeOfExprType *Canon
2033 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2034 if (Canon) {
2035 // We already have a "canonical" version of an identical, dependent
2036 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002037 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002038 QualType((TypeOfExprType*)Canon, 0));
2039 }
2040 else {
2041 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002042 Canon
2043 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002044 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2045 toe = Canon;
2046 }
2047 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002048 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002049 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002050 }
Steve Naroff9752f252007-08-01 18:02:17 +00002051 Types.push_back(toe);
2052 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002053}
2054
Steve Naroff9752f252007-08-01 18:02:17 +00002055/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2056/// TypeOfType AST's. The only motivation to unique these nodes would be
2057/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002058/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002059/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002060QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002061 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002062 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002063 Types.push_back(tot);
2064 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002065}
2066
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002067/// getDecltypeForExpr - Given an expr, will return the decltype for that
2068/// expression, according to the rules in C++0x [dcl.type.simple]p4
2069static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002070 if (e->isTypeDependent())
2071 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002073 // If e is an id expression or a class member access, decltype(e) is defined
2074 // as the type of the entity named by e.
2075 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2076 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2077 return VD->getType();
2078 }
2079 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2080 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2081 return FD->getType();
2082 }
2083 // If e is a function call or an invocation of an overloaded operator,
2084 // (parentheses around e are ignored), decltype(e) is defined as the
2085 // return type of that function.
2086 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2087 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002089 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002090
2091 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002092 // defined as T&, otherwise decltype(e) is defined as T.
2093 if (e->isLvalue(Context) == Expr::LV_Valid)
2094 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002096 return T;
2097}
2098
Anders Carlsson395b4752009-06-24 19:06:50 +00002099/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2100/// DecltypeType AST's. The only motivation to unique these nodes would be
2101/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002102/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002103/// on canonical type's (which are always unique).
2104QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002105 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002106 if (e->isTypeDependent()) {
2107 llvm::FoldingSetNodeID ID;
2108 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002110 void *InsertPos = 0;
2111 DependentDecltypeType *Canon
2112 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2113 if (Canon) {
2114 // We already have a "canonical" version of an equivalent, dependent
2115 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002116 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002117 QualType((DecltypeType*)Canon, 0));
2118 }
2119 else {
2120 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002121 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002122 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2123 dt = Canon;
2124 }
2125 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002126 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002127 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002128 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002129 Types.push_back(dt);
2130 return QualType(dt, 0);
2131}
2132
Reid Spencer5f016e22007-07-11 17:01:13 +00002133/// getTagDeclType - Return the unique reference to the type for the
2134/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002135QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002136 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002137 // FIXME: What is the design on getTagDeclType when it requires casting
2138 // away const? mutable?
2139 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002140}
2141
Mike Stump1eb44332009-09-09 15:08:12 +00002142/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2143/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2144/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002145QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002146 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002147}
2148
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002149/// getSignedWCharType - Return the type of "signed wchar_t".
2150/// Used when in C++, as a GCC extension.
2151QualType ASTContext::getSignedWCharType() const {
2152 // FIXME: derive from "Target" ?
2153 return WCharTy;
2154}
2155
2156/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2157/// Used when in C++, as a GCC extension.
2158QualType ASTContext::getUnsignedWCharType() const {
2159 // FIXME: derive from "Target" ?
2160 return UnsignedIntTy;
2161}
2162
Chris Lattner8b9023b2007-07-13 03:05:23 +00002163/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2164/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2165QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002166 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002167}
2168
Chris Lattnere6327742008-04-02 05:18:44 +00002169//===----------------------------------------------------------------------===//
2170// Type Operators
2171//===----------------------------------------------------------------------===//
2172
John McCall54e14c42009-10-22 22:37:11 +00002173CanQualType ASTContext::getCanonicalParamType(QualType T) {
2174 // Push qualifiers into arrays, and then discard any remaining
2175 // qualifiers.
2176 T = getCanonicalType(T);
2177 const Type *Ty = T.getTypePtr();
2178
2179 QualType Result;
2180 if (isa<ArrayType>(Ty)) {
2181 Result = getArrayDecayedType(QualType(Ty,0));
2182 } else if (isa<FunctionType>(Ty)) {
2183 Result = getPointerType(QualType(Ty, 0));
2184 } else {
2185 Result = QualType(Ty, 0);
2186 }
2187
2188 return CanQualType::CreateUnsafe(Result);
2189}
2190
Chris Lattner77c96472008-04-06 22:41:35 +00002191/// getCanonicalType - Return the canonical (structural) type corresponding to
2192/// the specified potentially non-canonical type. The non-canonical version
2193/// of a type may have many "decorated" versions of types. Decorators can
2194/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2195/// to be free of any of these, allowing two canonical types to be compared
2196/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002197CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002198 QualifierCollector Quals;
2199 const Type *Ptr = Quals.strip(T);
2200 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
John McCall0953e762009-09-24 19:53:00 +00002202 // The canonical internal type will be the canonical type *except*
2203 // that we push type qualifiers down through array types.
2204
2205 // If there are no new qualifiers to push down, stop here.
2206 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002207 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002208
John McCall0953e762009-09-24 19:53:00 +00002209 // If the type qualifiers are on an array type, get the canonical
2210 // type of the array with the qualifiers applied to the element
2211 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002212 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2213 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002214 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002216 // Get the canonical version of the element with the extra qualifiers on it.
2217 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002218 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002219 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002221 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002222 return CanQualType::CreateUnsafe(
2223 getConstantArrayType(NewEltTy, CAT->getSize(),
2224 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002225 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002226 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002227 return CanQualType::CreateUnsafe(
2228 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002229 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Douglas Gregor898574e2008-12-05 23:32:09 +00002231 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002232 return CanQualType::CreateUnsafe(
2233 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002234 DSAT->getSizeExpr() ?
2235 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002236 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002237 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002238 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002239
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002240 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002241 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002242 VAT->getSizeExpr() ?
2243 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002244 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002245 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002246 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002247}
2248
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002249TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2250 // If this template name refers to a template, the canonical
2251 // template name merely stores the template itself.
2252 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002253 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002254
Mike Stump1eb44332009-09-09 15:08:12 +00002255 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002256 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002257 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2258 OverloadedFunctionDecl *CanonOvl = 0;
2259 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2260 FEnd = Ovl->function_end();
2261 F != FEnd; ++F) {
2262 Decl *Canon = F->get()->getCanonicalDecl();
2263 if (CanonOvl || Canon != F->get()) {
2264 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002265 CanonOvl = OverloadedFunctionDecl::Create(*this,
2266 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002267 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002269 CanonOvl->addOverload(
2270 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2271 }
2272 }
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002274 return TemplateName(CanonOvl? CanonOvl : Ovl);
2275 }
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002277 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2278 assert(DTN && "Non-dependent template names must refer to template decls.");
2279 return DTN->CanonicalTemplateName;
2280}
2281
Mike Stump1eb44332009-09-09 15:08:12 +00002282TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002283ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2284 switch (Arg.getKind()) {
2285 case TemplateArgument::Null:
2286 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregor1275ae02009-07-28 23:00:59 +00002288 case TemplateArgument::Expression:
2289 // FIXME: Build canonical expression?
2290 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Douglas Gregor1275ae02009-07-28 23:00:59 +00002292 case TemplateArgument::Declaration:
2293 return TemplateArgument(SourceLocation(),
2294 Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Douglas Gregor1275ae02009-07-28 23:00:59 +00002296 case TemplateArgument::Integral:
2297 return TemplateArgument(SourceLocation(),
2298 *Arg.getAsIntegral(),
2299 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Douglas Gregor1275ae02009-07-28 23:00:59 +00002301 case TemplateArgument::Type:
2302 return TemplateArgument(SourceLocation(),
2303 getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Douglas Gregor1275ae02009-07-28 23:00:59 +00002305 case TemplateArgument::Pack: {
2306 // FIXME: Allocate in ASTContext
2307 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2308 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002309 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002310 AEnd = Arg.pack_end();
2311 A != AEnd; (void)++A, ++Idx)
2312 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Douglas Gregor1275ae02009-07-28 23:00:59 +00002314 TemplateArgument Result;
2315 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2316 return Result;
2317 }
2318 }
2319
2320 // Silence GCC warning
2321 assert(false && "Unhandled template argument kind");
2322 return TemplateArgument();
2323}
2324
Douglas Gregord57959a2009-03-27 23:10:48 +00002325NestedNameSpecifier *
2326ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002327 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002328 return 0;
2329
2330 switch (NNS->getKind()) {
2331 case NestedNameSpecifier::Identifier:
2332 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002333 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002334 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2335 NNS->getAsIdentifier());
2336
2337 case NestedNameSpecifier::Namespace:
2338 // A namespace is canonical; build a nested-name-specifier with
2339 // this namespace and no prefix.
2340 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2341
2342 case NestedNameSpecifier::TypeSpec:
2343 case NestedNameSpecifier::TypeSpecWithTemplate: {
2344 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002345 return NestedNameSpecifier::Create(*this, 0,
2346 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002347 T.getTypePtr());
2348 }
2349
2350 case NestedNameSpecifier::Global:
2351 // The global specifier is canonical and unique.
2352 return NNS;
2353 }
2354
2355 // Required to silence a GCC warning
2356 return 0;
2357}
2358
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002359
2360const ArrayType *ASTContext::getAsArrayType(QualType T) {
2361 // Handle the non-qualified case efficiently.
John McCall0953e762009-09-24 19:53:00 +00002362 if (!T.hasQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002363 // Handle the common positive case fast.
2364 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2365 return AT;
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
John McCall0953e762009-09-24 19:53:00 +00002368 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002369 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002370 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002371 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002372
John McCall0953e762009-09-24 19:53:00 +00002373 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002374 // implements C99 6.7.3p8: "If the specification of an array type includes
2375 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002376
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002377 // If we get here, we either have type qualifiers on the type, or we have
2378 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002379 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002380
John McCall0953e762009-09-24 19:53:00 +00002381 QualifierCollector Qs;
2382 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002384 // If we have a simple case, just return now.
2385 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002386 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002387 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002389 // Otherwise, we have an array and we have qualifiers on it. Push the
2390 // qualifiers into the array element type and return a new array type.
2391 // Get the canonical version of the element with the extra qualifiers on it.
2392 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002393 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002395 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2396 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2397 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002398 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002399 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2400 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2401 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002402 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002403
Mike Stump1eb44332009-09-09 15:08:12 +00002404 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002405 = dyn_cast<DependentSizedArrayType>(ATy))
2406 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002407 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002408 DSAT->getSizeExpr() ?
2409 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002410 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002411 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002412 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002414 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002415 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002416 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002417 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002418 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002419 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002420 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002421}
2422
2423
Chris Lattnere6327742008-04-02 05:18:44 +00002424/// getArrayDecayedType - Return the properly qualified result of decaying the
2425/// specified array type to a pointer. This operation is non-trivial when
2426/// handling typedefs etc. The canonical type of "T" must be an array type,
2427/// this returns a pointer to a properly qualified element of the array.
2428///
2429/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2430QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002431 // Get the element type with 'getAsArrayType' so that we don't lose any
2432 // typedefs in the element type of the array. This also handles propagation
2433 // of type qualifiers from the array type into the element type if present
2434 // (C99 6.7.3p8).
2435 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2436 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002438 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002439
2440 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002441 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002442}
2443
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002444QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002445 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002446 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002447 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002448 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2449 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002450 } else {
John McCall0953e762009-09-24 19:53:00 +00002451 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002452 }
2453 }
2454}
2455
Anders Carlssonfbbce492009-09-25 01:23:32 +00002456QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2457 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002458
Anders Carlssonfbbce492009-09-25 01:23:32 +00002459 if (const ArrayType *AT = getAsArrayType(ElemTy))
2460 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Anders Carlsson6183a992008-12-21 03:44:36 +00002462 return ElemTy;
2463}
2464
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002465/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002466uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002467ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2468 uint64_t ElementCount = 1;
2469 do {
2470 ElementCount *= CA->getSize().getZExtValue();
2471 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2472 } while (CA);
2473 return ElementCount;
2474}
2475
Reid Spencer5f016e22007-07-11 17:01:13 +00002476/// getFloatingRank - Return a relative rank for floating point types.
2477/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002478static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002479 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002481
John McCall183700f2009-09-21 23:43:11 +00002482 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2483 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002484 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 case BuiltinType::Float: return FloatRank;
2486 case BuiltinType::Double: return DoubleRank;
2487 case BuiltinType::LongDouble: return LongDoubleRank;
2488 }
2489}
2490
Mike Stump1eb44332009-09-09 15:08:12 +00002491/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2492/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002493/// 'typeDomain' is a real floating point or complex type.
2494/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002495QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2496 QualType Domain) const {
2497 FloatingRank EltRank = getFloatingRank(Size);
2498 if (Domain->isComplexType()) {
2499 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002500 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002501 case FloatRank: return FloatComplexTy;
2502 case DoubleRank: return DoubleComplexTy;
2503 case LongDoubleRank: return LongDoubleComplexTy;
2504 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 }
Chris Lattner1361b112008-04-06 23:58:54 +00002506
2507 assert(Domain->isRealFloatingType() && "Unknown domain!");
2508 switch (EltRank) {
2509 default: assert(0 && "getFloatingRank(): illegal value for rank");
2510 case FloatRank: return FloatTy;
2511 case DoubleRank: return DoubleTy;
2512 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002513 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002514}
2515
Chris Lattner7cfeb082008-04-06 23:55:33 +00002516/// getFloatingTypeOrder - Compare the rank of the two specified floating
2517/// point types, ignoring the domain of the type (i.e. 'double' ==
2518/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002519/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002520int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2521 FloatingRank LHSR = getFloatingRank(LHS);
2522 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002523
Chris Lattnera75cea32008-04-06 23:38:49 +00002524 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002525 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002526 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002527 return 1;
2528 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002529}
2530
Chris Lattnerf52ab252008-04-06 22:59:24 +00002531/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2532/// routine will assert if passed a built-in type that isn't an integer or enum,
2533/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002534unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002535 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002536 if (EnumType* ET = dyn_cast<EnumType>(T))
2537 T = ET->getDecl()->getIntegerType().getTypePtr();
2538
Eli Friedmana3426752009-07-05 23:44:27 +00002539 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2540 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2541
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002542 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2543 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2544
2545 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2546 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2547
Eli Friedmanf98aba32009-02-13 02:31:07 +00002548 // There are two things which impact the integer rank: the width, and
2549 // the ordering of builtins. The builtin ordering is encoded in the
2550 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002551 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002552 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002553
Chris Lattnerf52ab252008-04-06 22:59:24 +00002554 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002555 default: assert(0 && "getIntegerRank(): not a built-in integer");
2556 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002557 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002558 case BuiltinType::Char_S:
2559 case BuiltinType::Char_U:
2560 case BuiltinType::SChar:
2561 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002562 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002563 case BuiltinType::Short:
2564 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002565 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002566 case BuiltinType::Int:
2567 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002568 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002569 case BuiltinType::Long:
2570 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002571 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002572 case BuiltinType::LongLong:
2573 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002574 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002575 case BuiltinType::Int128:
2576 case BuiltinType::UInt128:
2577 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002578 }
2579}
2580
Eli Friedman04e83572009-08-20 04:21:42 +00002581/// \brief Whether this is a promotable bitfield reference according
2582/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2583///
2584/// \returns the type this bit-field will promote to, or NULL if no
2585/// promotion occurs.
2586QualType ASTContext::isPromotableBitField(Expr *E) {
2587 FieldDecl *Field = E->getBitField();
2588 if (!Field)
2589 return QualType();
2590
2591 QualType FT = Field->getType();
2592
2593 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2594 uint64_t BitWidth = BitWidthAP.getZExtValue();
2595 uint64_t IntSize = getTypeSize(IntTy);
2596 // GCC extension compatibility: if the bit-field size is less than or equal
2597 // to the size of int, it gets promoted no matter what its type is.
2598 // For instance, unsigned long bf : 4 gets promoted to signed int.
2599 if (BitWidth < IntSize)
2600 return IntTy;
2601
2602 if (BitWidth == IntSize)
2603 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2604
2605 // Types bigger than int are not subject to promotions, and therefore act
2606 // like the base type.
2607 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2608 // is ridiculous.
2609 return QualType();
2610}
2611
Eli Friedmana95d7572009-08-19 07:44:53 +00002612/// getPromotedIntegerType - Returns the type that Promotable will
2613/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2614/// integer type.
2615QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2616 assert(!Promotable.isNull());
2617 assert(Promotable->isPromotableIntegerType());
2618 if (Promotable->isSignedIntegerType())
2619 return IntTy;
2620 uint64_t PromotableSize = getTypeSize(Promotable);
2621 uint64_t IntSize = getTypeSize(IntTy);
2622 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2623 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2624}
2625
Mike Stump1eb44332009-09-09 15:08:12 +00002626/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002627/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002628/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002629int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002630 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2631 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002632 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Chris Lattnerf52ab252008-04-06 22:59:24 +00002634 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2635 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Chris Lattner7cfeb082008-04-06 23:55:33 +00002637 unsigned LHSRank = getIntegerRank(LHSC);
2638 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Chris Lattner7cfeb082008-04-06 23:55:33 +00002640 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2641 if (LHSRank == RHSRank) return 0;
2642 return LHSRank > RHSRank ? 1 : -1;
2643 }
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Chris Lattner7cfeb082008-04-06 23:55:33 +00002645 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2646 if (LHSUnsigned) {
2647 // If the unsigned [LHS] type is larger, return it.
2648 if (LHSRank >= RHSRank)
2649 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Chris Lattner7cfeb082008-04-06 23:55:33 +00002651 // If the signed type can represent all values of the unsigned type, it
2652 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002653 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002654 return -1;
2655 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002656
Chris Lattner7cfeb082008-04-06 23:55:33 +00002657 // If the unsigned [RHS] type is larger, return it.
2658 if (RHSRank >= LHSRank)
2659 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Chris Lattner7cfeb082008-04-06 23:55:33 +00002661 // If the signed type can represent all values of the unsigned type, it
2662 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002663 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002664 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002665}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002666
Mike Stump1eb44332009-09-09 15:08:12 +00002667// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002668QualType ASTContext::getCFConstantStringType() {
2669 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002670 CFConstantStringTypeDecl =
2671 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002672 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002673 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Anders Carlsson71993dd2007-08-17 05:31:46 +00002675 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002676 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002677 // int flags;
2678 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002679 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002680 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002681 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002682 FieldTypes[3] = LongTy;
2683
Anders Carlsson71993dd2007-08-17 05:31:46 +00002684 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002685 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002686 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002687 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002688 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002689 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002690 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002691 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002692 }
2693
2694 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002695 }
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Anders Carlsson71993dd2007-08-17 05:31:46 +00002697 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002698}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002699
Douglas Gregor319ac892009-04-23 22:29:11 +00002700void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002701 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002702 assert(Rec && "Invalid CFConstantStringType");
2703 CFConstantStringTypeDecl = Rec->getDecl();
2704}
2705
Mike Stump1eb44332009-09-09 15:08:12 +00002706QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002707 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002708 ObjCFastEnumerationStateTypeDecl =
2709 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2710 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002712 QualType FieldTypes[] = {
2713 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002714 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002715 getPointerType(UnsignedLongTy),
2716 getConstantArrayType(UnsignedLongTy,
2717 llvm::APInt(32, 5), ArrayType::Normal, 0)
2718 };
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregor44b43212008-12-11 16:49:14 +00002720 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002721 FieldDecl *Field = FieldDecl::Create(*this,
2722 ObjCFastEnumerationStateTypeDecl,
2723 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002724 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002725 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002726 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002727 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002728 }
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregor44b43212008-12-11 16:49:14 +00002730 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002731 }
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002733 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2734}
2735
Mike Stumpadaaad32009-10-20 02:12:22 +00002736QualType ASTContext::getBlockDescriptorType() {
2737 if (BlockDescriptorType)
2738 return getTagDeclType(BlockDescriptorType);
2739
2740 RecordDecl *T;
2741 // FIXME: Needs the FlagAppleBlock bit.
2742 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2743 &Idents.get("__block_descriptor"));
2744
2745 QualType FieldTypes[] = {
2746 UnsignedLongTy,
2747 UnsignedLongTy,
2748 };
2749
2750 const char *FieldNames[] = {
2751 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002752 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002753 };
2754
2755 for (size_t i = 0; i < 2; ++i) {
2756 FieldDecl *Field = FieldDecl::Create(*this,
2757 T,
2758 SourceLocation(),
2759 &Idents.get(FieldNames[i]),
2760 FieldTypes[i], /*DInfo=*/0,
2761 /*BitWidth=*/0,
2762 /*Mutable=*/false);
2763 T->addDecl(Field);
2764 }
2765
2766 T->completeDefinition(*this);
2767
2768 BlockDescriptorType = T;
2769
2770 return getTagDeclType(BlockDescriptorType);
2771}
2772
2773void ASTContext::setBlockDescriptorType(QualType T) {
2774 const RecordType *Rec = T->getAs<RecordType>();
2775 assert(Rec && "Invalid BlockDescriptorType");
2776 BlockDescriptorType = Rec->getDecl();
2777}
2778
Mike Stump083c25e2009-10-22 00:49:09 +00002779QualType ASTContext::getBlockDescriptorExtendedType() {
2780 if (BlockDescriptorExtendedType)
2781 return getTagDeclType(BlockDescriptorExtendedType);
2782
2783 RecordDecl *T;
2784 // FIXME: Needs the FlagAppleBlock bit.
2785 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2786 &Idents.get("__block_descriptor_withcopydispose"));
2787
2788 QualType FieldTypes[] = {
2789 UnsignedLongTy,
2790 UnsignedLongTy,
2791 getPointerType(VoidPtrTy),
2792 getPointerType(VoidPtrTy)
2793 };
2794
2795 const char *FieldNames[] = {
2796 "reserved",
2797 "Size",
2798 "CopyFuncPtr",
2799 "DestroyFuncPtr"
2800 };
2801
2802 for (size_t i = 0; i < 4; ++i) {
2803 FieldDecl *Field = FieldDecl::Create(*this,
2804 T,
2805 SourceLocation(),
2806 &Idents.get(FieldNames[i]),
2807 FieldTypes[i], /*DInfo=*/0,
2808 /*BitWidth=*/0,
2809 /*Mutable=*/false);
2810 T->addDecl(Field);
2811 }
2812
2813 T->completeDefinition(*this);
2814
2815 BlockDescriptorExtendedType = T;
2816
2817 return getTagDeclType(BlockDescriptorExtendedType);
2818}
2819
2820void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2821 const RecordType *Rec = T->getAs<RecordType>();
2822 assert(Rec && "Invalid BlockDescriptorType");
2823 BlockDescriptorExtendedType = Rec->getDecl();
2824}
2825
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002826bool ASTContext::BlockRequiresCopying(QualType Ty) {
2827 if (Ty->isBlockPointerType())
2828 return true;
2829 if (isObjCNSObjectType(Ty))
2830 return true;
2831 if (Ty->isObjCObjectPointerType())
2832 return true;
2833 return false;
2834}
2835
2836QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2837 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002838 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002839 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002840 // unsigned int __flags;
2841 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002842 // void *__copy_helper; // as needed
2843 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002844 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002845 // } *
2846
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002847 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2848
2849 // FIXME: Move up
2850 static int UniqueBlockByRefTypeID = 0;
2851 char Name[36];
2852 sprintf(Name, "__Block_byref_%d_%s", ++UniqueBlockByRefTypeID, DeclName);
2853 RecordDecl *T;
2854 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2855 &Idents.get(Name));
2856 T->startDefinition();
2857 QualType Int32Ty = IntTy;
2858 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2859 QualType FieldTypes[] = {
2860 getPointerType(VoidPtrTy),
2861 getPointerType(getTagDeclType(T)),
2862 Int32Ty,
2863 Int32Ty,
2864 getPointerType(VoidPtrTy),
2865 getPointerType(VoidPtrTy),
2866 Ty
2867 };
2868
2869 const char *FieldNames[] = {
2870 "__isa",
2871 "__forwarding",
2872 "__flags",
2873 "__size",
2874 "__copy_helper",
2875 "__destroy_helper",
2876 DeclName,
2877 };
2878
2879 for (size_t i = 0; i < 7; ++i) {
2880 if (!HasCopyAndDispose && i >=4 && i <= 5)
2881 continue;
2882 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2883 &Idents.get(FieldNames[i]),
2884 FieldTypes[i], /*DInfo=*/0,
2885 /*BitWidth=*/0, /*Mutable=*/false);
2886 T->addDecl(Field);
2887 }
2888
2889 T->completeDefinition(*this);
2890
2891 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002892}
2893
2894
2895QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002896 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002897 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002898 // FIXME: Move up
2899 static int UniqueBlockParmTypeID = 0;
2900 char Name[36];
2901 sprintf(Name, "__block_literal_%u", ++UniqueBlockParmTypeID);
2902 RecordDecl *T;
2903 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2904 &Idents.get(Name));
Mike Stumpadaaad32009-10-20 02:12:22 +00002905 QualType FieldTypes[] = {
2906 getPointerType(VoidPtrTy),
2907 IntTy,
2908 IntTy,
2909 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00002910 (BlockHasCopyDispose ?
2911 getPointerType(getBlockDescriptorExtendedType()) :
2912 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00002913 };
2914
2915 const char *FieldNames[] = {
2916 "__isa",
2917 "__flags",
2918 "__reserved",
2919 "__FuncPtr",
2920 "__descriptor"
2921 };
2922
2923 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00002924 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00002925 &Idents.get(FieldNames[i]),
2926 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00002927 /*BitWidth=*/0, /*Mutable=*/false);
2928 T->addDecl(Field);
2929 }
2930
2931 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
2932 const Expr *E = BlockDeclRefDecls[i];
2933 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2934 clang::IdentifierInfo *Name = 0;
2935 if (BDRE) {
2936 const ValueDecl *D = BDRE->getDecl();
2937 Name = &Idents.get(D->getName());
2938 }
2939 QualType FieldType = E->getType();
2940
2941 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002942 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
2943 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00002944
2945 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2946 Name, FieldType, /*DInfo=*/0,
2947 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00002948 T->addDecl(Field);
2949 }
2950
2951 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00002952
2953 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00002954}
2955
Douglas Gregor319ac892009-04-23 22:29:11 +00002956void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002957 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002958 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2959 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2960}
2961
Anders Carlssone8c49532007-10-29 06:33:42 +00002962// This returns true if a type has been typedefed to BOOL:
2963// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002964static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002965 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002966 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2967 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002969 return false;
2970}
2971
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002972/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002973/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002974int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002975 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002977 // Make all integer and enum types at least as large as an int
2978 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002979 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002980 // Treat arrays as pointers, since that's how they're passed in.
2981 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002982 sz = getTypeSize(VoidPtrTy);
2983 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002984}
2985
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002986/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002987/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002988void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002989 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002990 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002991 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002992 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002993 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002994 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002995 // Compute size of all parameters.
2996 // Start with computing size of a pointer in number of bytes.
2997 // FIXME: There might(should) be a better way of doing this computation!
2998 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002999 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003000 // The first two arguments (self and _cmd) are pointers; account for
3001 // their size.
3002 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003003 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3004 E = Decl->param_end(); PI != E; ++PI) {
3005 QualType PType = (*PI)->getType();
3006 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003007 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003008 ParmOffset += sz;
3009 }
3010 S += llvm::utostr(ParmOffset);
3011 S += "@0:";
3012 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003014 // Argument types.
3015 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003016 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3017 E = Decl->param_end(); PI != E; ++PI) {
3018 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003019 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003020 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003021 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3022 // Use array's original type only if it has known number of
3023 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003024 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003025 PType = PVDecl->getType();
3026 } else if (PType->isFunctionType())
3027 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003028 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003029 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003030 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003031 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003032 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003033 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003034 }
3035}
3036
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003037/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003038/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003039/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3040/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003041/// Property attributes are stored as a comma-delimited C string. The simple
3042/// attributes readonly and bycopy are encoded as single characters. The
3043/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3044/// encoded as single characters, followed by an identifier. Property types
3045/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003046/// these attributes are defined by the following enumeration:
3047/// @code
3048/// enum PropertyAttributes {
3049/// kPropertyReadOnly = 'R', // property is read-only.
3050/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3051/// kPropertyByref = '&', // property is a reference to the value last assigned
3052/// kPropertyDynamic = 'D', // property is dynamic
3053/// kPropertyGetter = 'G', // followed by getter selector name
3054/// kPropertySetter = 'S', // followed by setter selector name
3055/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3056/// kPropertyType = 't' // followed by old-style type encoding.
3057/// kPropertyWeak = 'W' // 'weak' property
3058/// kPropertyStrong = 'P' // property GC'able
3059/// kPropertyNonAtomic = 'N' // property non-atomic
3060/// };
3061/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003062void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003063 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003064 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003065 // Collect information from the property implementation decl(s).
3066 bool Dynamic = false;
3067 ObjCPropertyImplDecl *SynthesizePID = 0;
3068
3069 // FIXME: Duplicated code due to poor abstraction.
3070 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003071 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003072 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3073 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003074 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003075 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003076 ObjCPropertyImplDecl *PID = *i;
3077 if (PID->getPropertyDecl() == PD) {
3078 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3079 Dynamic = true;
3080 } else {
3081 SynthesizePID = PID;
3082 }
3083 }
3084 }
3085 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003086 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003087 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003088 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003089 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003090 ObjCPropertyImplDecl *PID = *i;
3091 if (PID->getPropertyDecl() == PD) {
3092 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3093 Dynamic = true;
3094 } else {
3095 SynthesizePID = PID;
3096 }
3097 }
Mike Stump1eb44332009-09-09 15:08:12 +00003098 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003099 }
3100 }
3101
3102 // FIXME: This is not very efficient.
3103 S = "T";
3104
3105 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003106 // GCC has some special rules regarding encoding of properties which
3107 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003108 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003109 true /* outermost type */,
3110 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003111
3112 if (PD->isReadOnly()) {
3113 S += ",R";
3114 } else {
3115 switch (PD->getSetterKind()) {
3116 case ObjCPropertyDecl::Assign: break;
3117 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003118 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003119 }
3120 }
3121
3122 // It really isn't clear at all what this means, since properties
3123 // are "dynamic by default".
3124 if (Dynamic)
3125 S += ",D";
3126
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003127 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3128 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003130 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3131 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003132 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003133 }
3134
3135 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3136 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003137 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003138 }
3139
3140 if (SynthesizePID) {
3141 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3142 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003143 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003144 }
3145
3146 // FIXME: OBJCGC: weak & strong
3147}
3148
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003149/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003150/// Another legacy compatibility encoding: 32-bit longs are encoded as
3151/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003152/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3153///
3154void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003155 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003156 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003157 if (BT->getKind() == BuiltinType::ULong &&
3158 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003159 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003160 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003161 if (BT->getKind() == BuiltinType::Long &&
3162 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003163 PointeeTy = IntTy;
3164 }
3165 }
3166}
3167
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003168void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003169 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003170 // We follow the behavior of gcc, expanding structures which are
3171 // directly pointed to, and expanding embedded structures. Note that
3172 // these rules are sufficient to prevent recursive encoding of the
3173 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003174 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003175 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003176}
3177
Mike Stump1eb44332009-09-09 15:08:12 +00003178static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003179 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003180 const Expr *E = FD->getBitWidth();
3181 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3182 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003183 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003184 S += 'b';
3185 S += llvm::utostr(N);
3186}
3187
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003188// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003189void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3190 bool ExpandPointedToStructures,
3191 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003192 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003193 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003194 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003195 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003196 if (FD && FD->isBitField())
3197 return EncodeBitField(this, S, FD);
3198 char encoding;
3199 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003200 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003201 case BuiltinType::Void: encoding = 'v'; break;
3202 case BuiltinType::Bool: encoding = 'B'; break;
3203 case BuiltinType::Char_U:
3204 case BuiltinType::UChar: encoding = 'C'; break;
3205 case BuiltinType::UShort: encoding = 'S'; break;
3206 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003207 case BuiltinType::ULong:
3208 encoding =
3209 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003210 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003211 case BuiltinType::UInt128: encoding = 'T'; break;
3212 case BuiltinType::ULongLong: encoding = 'Q'; break;
3213 case BuiltinType::Char_S:
3214 case BuiltinType::SChar: encoding = 'c'; break;
3215 case BuiltinType::Short: encoding = 's'; break;
3216 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003217 case BuiltinType::Long:
3218 encoding =
3219 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003220 break;
3221 case BuiltinType::LongLong: encoding = 'q'; break;
3222 case BuiltinType::Int128: encoding = 't'; break;
3223 case BuiltinType::Float: encoding = 'f'; break;
3224 case BuiltinType::Double: encoding = 'd'; break;
3225 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003226 }
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003228 S += encoding;
3229 return;
3230 }
Mike Stump1eb44332009-09-09 15:08:12 +00003231
John McCall183700f2009-09-21 23:43:11 +00003232 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003233 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003234 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003235 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003236 return;
3237 }
Mike Stump1eb44332009-09-09 15:08:12 +00003238
Ted Kremenek6217b802009-07-29 21:53:49 +00003239 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003240 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003241 bool isReadOnly = false;
3242 // For historical/compatibility reasons, the read-only qualifier of the
3243 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3244 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003245 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003246 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003247 if (OutermostType && T.isConstQualified()) {
3248 isReadOnly = true;
3249 S += 'r';
3250 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003251 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003252 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003253 while (P->getAs<PointerType>())
3254 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003255 if (P.isConstQualified()) {
3256 isReadOnly = true;
3257 S += 'r';
3258 }
3259 }
3260 if (isReadOnly) {
3261 // Another legacy compatibility encoding. Some ObjC qualifier and type
3262 // combinations need to be rearranged.
3263 // Rewrite "in const" from "nr" to "rn"
3264 const char * s = S.c_str();
3265 int len = S.length();
3266 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3267 std::string replace = "rn";
3268 S.replace(S.end()-2, S.end(), replace);
3269 }
3270 }
Steve Naroff14108da2009-07-10 23:34:53 +00003271 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003272 S += ':';
3273 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003274 }
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003276 if (PointeeTy->isCharType()) {
3277 // char pointer types should be encoded as '*' unless it is a
3278 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003279 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003280 S += '*';
3281 return;
3282 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003283 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003284 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3285 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3286 S += '#';
3287 return;
3288 }
3289 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3290 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3291 S += '@';
3292 return;
3293 }
3294 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003295 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003296 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003297 getLegacyIntegralTypeEncoding(PointeeTy);
3298
Mike Stump1eb44332009-09-09 15:08:12 +00003299 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003300 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003301 return;
3302 }
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003304 if (const ArrayType *AT =
3305 // Ignore type qualifiers etc.
3306 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003307 if (isa<IncompleteArrayType>(AT)) {
3308 // Incomplete arrays are encoded as a pointer to the array element.
3309 S += '^';
3310
Mike Stump1eb44332009-09-09 15:08:12 +00003311 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003312 false, ExpandStructures, FD);
3313 } else {
3314 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003315
Anders Carlsson559a8332009-02-22 01:38:57 +00003316 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3317 S += llvm::utostr(CAT->getSize().getZExtValue());
3318 else {
3319 //Variable length arrays are encoded as a regular array with 0 elements.
3320 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3321 S += '0';
3322 }
Mike Stump1eb44332009-09-09 15:08:12 +00003323
3324 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003325 false, ExpandStructures, FD);
3326 S += ']';
3327 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003328 return;
3329 }
Mike Stump1eb44332009-09-09 15:08:12 +00003330
John McCall183700f2009-09-21 23:43:11 +00003331 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003332 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003333 return;
3334 }
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Ted Kremenek6217b802009-07-29 21:53:49 +00003336 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003337 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003338 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003339 // Anonymous structures print as '?'
3340 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3341 S += II->getName();
3342 } else {
3343 S += '?';
3344 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003345 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003346 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003347 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3348 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003349 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003350 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003351 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003352 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003353 S += '"';
3354 }
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003356 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003357 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003358 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003359 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003360 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003361 QualType qt = Field->getType();
3362 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003363 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003364 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003365 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003366 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003367 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003368 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003369 return;
3370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003372 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003373 if (FD && FD->isBitField())
3374 EncodeBitField(this, S, FD);
3375 else
3376 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003377 return;
3378 }
Mike Stump1eb44332009-09-09 15:08:12 +00003379
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003380 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003381 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003382 return;
3383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
John McCall0953e762009-09-24 19:53:00 +00003385 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003386 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003387 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003388 S += '{';
3389 const IdentifierInfo *II = OI->getIdentifier();
3390 S += II->getName();
3391 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003392 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003393 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003394 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003395 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003396 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003397 RecFields[i]);
3398 else
Mike Stump1eb44332009-09-09 15:08:12 +00003399 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003400 FD);
3401 }
3402 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003403 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003404 }
Mike Stump1eb44332009-09-09 15:08:12 +00003405
John McCall183700f2009-09-21 23:43:11 +00003406 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003407 if (OPT->isObjCIdType()) {
3408 S += '@';
3409 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003410 }
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003412 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003413 S += '#';
3414 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003415 }
Mike Stump1eb44332009-09-09 15:08:12 +00003416
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003417 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003418 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003419 ExpandPointedToStructures,
3420 ExpandStructures, FD);
3421 if (FD || EncodingProperty) {
3422 // Note that we do extended encoding of protocol qualifer list
3423 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003424 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003425 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3426 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003427 S += '<';
3428 S += (*I)->getNameAsString();
3429 S += '>';
3430 }
3431 S += '"';
3432 }
3433 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003436 QualType PointeeTy = OPT->getPointeeType();
3437 if (!EncodingProperty &&
3438 isa<TypedefType>(PointeeTy.getTypePtr())) {
3439 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003440 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003441 // {...};
3442 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003443 getObjCEncodingForTypeImpl(PointeeTy, S,
3444 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003445 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003446 return;
3447 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003448
3449 S += '@';
3450 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003451 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003452 S += OPT->getInterfaceDecl()->getNameAsCString();
3453 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3454 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003455 S += '<';
3456 S += (*I)->getNameAsString();
3457 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003458 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003459 S += '"';
3460 }
3461 return;
3462 }
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003464 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003465}
3466
Mike Stump1eb44332009-09-09 15:08:12 +00003467void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003468 std::string& S) const {
3469 if (QT & Decl::OBJC_TQ_In)
3470 S += 'n';
3471 if (QT & Decl::OBJC_TQ_Inout)
3472 S += 'N';
3473 if (QT & Decl::OBJC_TQ_Out)
3474 S += 'o';
3475 if (QT & Decl::OBJC_TQ_Bycopy)
3476 S += 'O';
3477 if (QT & Decl::OBJC_TQ_Byref)
3478 S += 'R';
3479 if (QT & Decl::OBJC_TQ_Oneway)
3480 S += 'V';
3481}
3482
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003483void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003484 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003486 BuiltinVaListType = T;
3487}
3488
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003489void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003490 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003491}
3492
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003493void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003494 ObjCSelType = T;
3495
John McCall183700f2009-09-21 23:43:11 +00003496 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003497 if (!TT)
3498 return;
3499 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003500
3501 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003502 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003503 if (!ptr)
3504 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003505 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003506 if (!rec)
3507 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003508 SelStructType = rec;
3509}
3510
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003511void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003512 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003513}
3514
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003515void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003516 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003517}
3518
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003519void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003520 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003521 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003523 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003524}
3525
Douglas Gregor7532dc62009-03-30 22:58:21 +00003526/// \brief Retrieve the template name that represents a qualified
3527/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003528TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003529 bool TemplateKeyword,
3530 TemplateDecl *Template) {
3531 llvm::FoldingSetNodeID ID;
3532 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3533
3534 void *InsertPos = 0;
3535 QualifiedTemplateName *QTN =
3536 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3537 if (!QTN) {
3538 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3539 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3540 }
3541
3542 return TemplateName(QTN);
3543}
3544
Douglas Gregord99cbe62009-07-29 18:26:50 +00003545/// \brief Retrieve the template name that represents a qualified
3546/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003547TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003548 bool TemplateKeyword,
3549 OverloadedFunctionDecl *Template) {
3550 llvm::FoldingSetNodeID ID;
3551 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Douglas Gregord99cbe62009-07-29 18:26:50 +00003553 void *InsertPos = 0;
3554 QualifiedTemplateName *QTN =
3555 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3556 if (!QTN) {
3557 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3558 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Douglas Gregord99cbe62009-07-29 18:26:50 +00003561 return TemplateName(QTN);
3562}
3563
Douglas Gregor7532dc62009-03-30 22:58:21 +00003564/// \brief Retrieve the template name that represents a dependent
3565/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003566TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003567 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003568 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003569 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003570
3571 llvm::FoldingSetNodeID ID;
3572 DependentTemplateName::Profile(ID, NNS, Name);
3573
3574 void *InsertPos = 0;
3575 DependentTemplateName *QTN =
3576 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3577
3578 if (QTN)
3579 return TemplateName(QTN);
3580
3581 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3582 if (CanonNNS == NNS) {
3583 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3584 } else {
3585 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3586 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3587 }
3588
3589 DependentTemplateNames.InsertNode(QTN, InsertPos);
3590 return TemplateName(QTN);
3591}
3592
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003593/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003594/// TargetInfo, produce the corresponding type. The unsigned @p Type
3595/// is actually a value of type @c TargetInfo::IntType.
3596QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003597 switch (Type) {
Mike Stump1eb44332009-09-09 15:08:12 +00003598 case TargetInfo::NoInt: return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003599 case TargetInfo::SignedShort: return ShortTy;
3600 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3601 case TargetInfo::SignedInt: return IntTy;
3602 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3603 case TargetInfo::SignedLong: return LongTy;
3604 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3605 case TargetInfo::SignedLongLong: return LongLongTy;
3606 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3607 }
3608
3609 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003610 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003611}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003612
3613//===----------------------------------------------------------------------===//
3614// Type Predicates.
3615//===----------------------------------------------------------------------===//
3616
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003617/// isObjCNSObjectType - Return true if this is an NSObject object using
3618/// NSObject attribute on a c-style pointer type.
3619/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003620/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003621///
3622bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3623 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3624 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003625 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003626 return true;
3627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003629}
3630
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003631/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3632/// garbage collection attribute.
3633///
John McCall0953e762009-09-24 19:53:00 +00003634Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3635 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003636 if (getLangOptions().ObjC1 &&
3637 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003638 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003639 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003640 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003641 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003642 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003643 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003644 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003645 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003646 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003647 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003648 // Non-pointers have none gc'able attribute regardless of the attribute
3649 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003650 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003651 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003652 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003653 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003654}
3655
Chris Lattner6ac46a42008-04-07 06:51:04 +00003656//===----------------------------------------------------------------------===//
3657// Type Compatibility Testing
3658//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003659
Mike Stump1eb44332009-09-09 15:08:12 +00003660/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003661/// compatible.
3662static bool areCompatVectorTypes(const VectorType *LHS,
3663 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003664 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003665 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003666 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003667}
3668
Steve Naroff4084c302009-07-23 01:01:38 +00003669//===----------------------------------------------------------------------===//
3670// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3671//===----------------------------------------------------------------------===//
3672
3673/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3674/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003675bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3676 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003677 if (lProto == rProto)
3678 return true;
3679 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3680 E = rProto->protocol_end(); PI != E; ++PI)
3681 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3682 return true;
3683 return false;
3684}
3685
Steve Naroff4084c302009-07-23 01:01:38 +00003686/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3687/// return true if lhs's protocols conform to rhs's protocol; false
3688/// otherwise.
3689bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3690 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3691 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3692 return false;
3693}
3694
3695/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3696/// ObjCQualifiedIDType.
3697bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3698 bool compare) {
3699 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003700 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003701 lhs->isObjCIdType() || lhs->isObjCClassType())
3702 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003703 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003704 rhs->isObjCIdType() || rhs->isObjCClassType())
3705 return true;
3706
3707 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003708 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Steve Naroff4084c302009-07-23 01:01:38 +00003710 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Steve Naroff4084c302009-07-23 01:01:38 +00003712 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003713 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003714 // make sure we check the class hierarchy.
3715 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3716 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3717 E = lhsQID->qual_end(); I != E; ++I) {
3718 // when comparing an id<P> on lhs with a static type on rhs,
3719 // see if static class implements all of id's protocols, directly or
3720 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003721 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003722 return false;
3723 }
3724 }
3725 // If there are no qualifiers and no interface, we have an 'id'.
3726 return true;
3727 }
Mike Stump1eb44332009-09-09 15:08:12 +00003728 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003729 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3730 E = lhsQID->qual_end(); I != E; ++I) {
3731 ObjCProtocolDecl *lhsProto = *I;
3732 bool match = false;
3733
3734 // when comparing an id<P> on lhs with a static type on rhs,
3735 // see if static class implements all of id's protocols, directly or
3736 // through its super class and categories.
3737 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3738 E = rhsOPT->qual_end(); J != E; ++J) {
3739 ObjCProtocolDecl *rhsProto = *J;
3740 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3741 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3742 match = true;
3743 break;
3744 }
3745 }
Mike Stump1eb44332009-09-09 15:08:12 +00003746 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003747 // make sure we check the class hierarchy.
3748 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3749 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3750 E = lhsQID->qual_end(); I != E; ++I) {
3751 // when comparing an id<P> on lhs with a static type on rhs,
3752 // see if static class implements all of id's protocols, directly or
3753 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003754 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003755 match = true;
3756 break;
3757 }
3758 }
3759 }
3760 if (!match)
3761 return false;
3762 }
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Steve Naroff4084c302009-07-23 01:01:38 +00003764 return true;
3765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Steve Naroff4084c302009-07-23 01:01:38 +00003767 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3768 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3769
Mike Stump1eb44332009-09-09 15:08:12 +00003770 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003771 lhs->getAsObjCInterfacePointerType()) {
3772 if (lhsOPT->qual_empty()) {
3773 bool match = false;
3774 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3775 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3776 E = rhsQID->qual_end(); I != E; ++I) {
3777 // when comparing an id<P> on lhs with a static type on rhs,
3778 // see if static class implements all of id's protocols, directly or
3779 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003780 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003781 match = true;
3782 break;
3783 }
3784 }
3785 if (!match)
3786 return false;
3787 }
3788 return true;
3789 }
Mike Stump1eb44332009-09-09 15:08:12 +00003790 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003791 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3792 E = lhsOPT->qual_end(); I != E; ++I) {
3793 ObjCProtocolDecl *lhsProto = *I;
3794 bool match = false;
3795
3796 // when comparing an id<P> on lhs with a static type on rhs,
3797 // see if static class implements all of id's protocols, directly or
3798 // through its super class and categories.
3799 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3800 E = rhsQID->qual_end(); J != E; ++J) {
3801 ObjCProtocolDecl *rhsProto = *J;
3802 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3803 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3804 match = true;
3805 break;
3806 }
3807 }
3808 if (!match)
3809 return false;
3810 }
3811 return true;
3812 }
3813 return false;
3814}
3815
Eli Friedman3d815e72008-08-22 00:56:42 +00003816/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003817/// compatible for assignment from RHS to LHS. This handles validation of any
3818/// protocol qualifiers on the LHS or RHS.
3819///
Steve Naroff14108da2009-07-10 23:34:53 +00003820bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3821 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003822 // If either type represents the built-in 'id' or 'Class' types, return true.
3823 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003824 return true;
3825
Steve Naroff4084c302009-07-23 01:01:38 +00003826 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003827 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3828 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003829 false);
3830
Steve Naroff14108da2009-07-10 23:34:53 +00003831 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3832 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003833 if (LHS && RHS) // We have 2 user-defined types.
3834 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Steve Naroff4084c302009-07-23 01:01:38 +00003836 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003837}
3838
Eli Friedman3d815e72008-08-22 00:56:42 +00003839bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3840 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003841 // Verify that the base decls are compatible: the RHS must be a subclass of
3842 // the LHS.
3843 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3844 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Chris Lattner6ac46a42008-04-07 06:51:04 +00003846 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3847 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003848 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003849 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Chris Lattner6ac46a42008-04-07 06:51:04 +00003851 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3852 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003853 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003854 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003856 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3857 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003858 LHSPI != LHSPE; LHSPI++) {
3859 bool RHSImplementsProtocol = false;
3860
3861 // If the RHS doesn't implement the protocol on the left, the types
3862 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003863 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003864 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003865 RHSPI != RHSPE; RHSPI++) {
3866 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003867 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003868 break;
3869 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003870 }
3871 // FIXME: For better diagnostics, consider passing back the protocol name.
3872 if (!RHSImplementsProtocol)
3873 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003874 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003875 // The RHS implements all protocols listed on the LHS.
3876 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003877}
3878
Steve Naroff389bf462009-02-12 17:52:19 +00003879bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3880 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00003881 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
3882 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Steve Naroff14108da2009-07-10 23:34:53 +00003884 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003885 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003886
3887 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3888 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003889}
3890
Mike Stump1eb44332009-09-09 15:08:12 +00003891/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00003892/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00003893/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00003894/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003895bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3896 return !mergeTypes(LHS, RHS).isNull();
3897}
3898
3899QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00003900 const FunctionType *lbase = lhs->getAs<FunctionType>();
3901 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00003902 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3903 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003904 bool allLTypes = true;
3905 bool allRTypes = true;
3906
3907 // Check return type
3908 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3909 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003910 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3911 allLTypes = false;
3912 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3913 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003914 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003915 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3916 if (NoReturn != lbase->getNoReturnAttr())
3917 allLTypes = false;
3918 if (NoReturn != rbase->getNoReturnAttr())
3919 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Eli Friedman3d815e72008-08-22 00:56:42 +00003921 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003922 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3923 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003924 unsigned lproto_nargs = lproto->getNumArgs();
3925 unsigned rproto_nargs = rproto->getNumArgs();
3926
3927 // Compatible functions must have the same number of arguments
3928 if (lproto_nargs != rproto_nargs)
3929 return QualType();
3930
3931 // Variadic and non-variadic functions aren't compatible
3932 if (lproto->isVariadic() != rproto->isVariadic())
3933 return QualType();
3934
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003935 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3936 return QualType();
3937
Eli Friedman3d815e72008-08-22 00:56:42 +00003938 // Check argument compatibility
3939 llvm::SmallVector<QualType, 10> types;
3940 for (unsigned i = 0; i < lproto_nargs; i++) {
3941 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3942 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3943 QualType argtype = mergeTypes(largtype, rargtype);
3944 if (argtype.isNull()) return QualType();
3945 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003946 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3947 allLTypes = false;
3948 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3949 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003950 }
3951 if (allLTypes) return lhs;
3952 if (allRTypes) return rhs;
3953 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003954 lproto->isVariadic(), lproto->getTypeQuals(),
3955 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003956 }
3957
3958 if (lproto) allRTypes = false;
3959 if (rproto) allLTypes = false;
3960
Douglas Gregor72564e72009-02-26 23:50:07 +00003961 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003962 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003963 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003964 if (proto->isVariadic()) return QualType();
3965 // Check that the types are compatible with the types that
3966 // would result from default argument promotions (C99 6.7.5.3p15).
3967 // The only types actually affected are promotable integer
3968 // types and floats, which would be passed as a different
3969 // type depending on whether the prototype is visible.
3970 unsigned proto_nargs = proto->getNumArgs();
3971 for (unsigned i = 0; i < proto_nargs; ++i) {
3972 QualType argTy = proto->getArgType(i);
3973 if (argTy->isPromotableIntegerType() ||
3974 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3975 return QualType();
3976 }
3977
3978 if (allLTypes) return lhs;
3979 if (allRTypes) return rhs;
3980 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003981 proto->getNumArgs(), proto->isVariadic(),
3982 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003983 }
3984
3985 if (allLTypes) return lhs;
3986 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003987 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003988}
3989
3990QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003991 // C++ [expr]: If an expression initially has the type "reference to T", the
3992 // type is adjusted to "T" prior to any further analysis, the expression
3993 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003994 // expression is an lvalue unless the reference is an rvalue reference and
3995 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003996 // FIXME: C++ shouldn't be going through here! The rules are different
3997 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003998 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3999 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004000 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004001 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004002 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004003 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004004
Eli Friedman3d815e72008-08-22 00:56:42 +00004005 QualType LHSCan = getCanonicalType(LHS),
4006 RHSCan = getCanonicalType(RHS);
4007
4008 // If two types are identical, they are compatible.
4009 if (LHSCan == RHSCan)
4010 return LHS;
4011
John McCall0953e762009-09-24 19:53:00 +00004012 // If the qualifiers are different, the types aren't compatible... mostly.
4013 Qualifiers LQuals = LHSCan.getQualifiers();
4014 Qualifiers RQuals = RHSCan.getQualifiers();
4015 if (LQuals != RQuals) {
4016 // If any of these qualifiers are different, we have a type
4017 // mismatch.
4018 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4019 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4020 return QualType();
4021
4022 // Exactly one GC qualifier difference is allowed: __strong is
4023 // okay if the other type has no GC qualifier but is an Objective
4024 // C object pointer (i.e. implicitly strong by default). We fix
4025 // this by pretending that the unqualified type was actually
4026 // qualified __strong.
4027 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4028 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4029 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4030
4031 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4032 return QualType();
4033
4034 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4035 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4036 }
4037 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4038 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4039 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004040 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004041 }
4042
4043 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004044
Eli Friedman852d63b2009-06-01 01:22:52 +00004045 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4046 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004047
Chris Lattner1adb8832008-01-14 05:45:46 +00004048 // We want to consider the two function types to be the same for these
4049 // comparisons, just force one to the other.
4050 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4051 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004052
4053 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004054 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4055 LHSClass = Type::ConstantArray;
4056 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4057 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004058
Nate Begeman213541a2008-04-18 23:10:10 +00004059 // Canonicalize ExtVector -> Vector.
4060 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4061 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004062
Chris Lattnera36a61f2008-04-07 05:43:21 +00004063 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004064 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004065 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004066 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004067 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004068 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4069 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004070 }
John McCall183700f2009-09-21 23:43:11 +00004071 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004072 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4073 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004074 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004075
Eli Friedman3d815e72008-08-22 00:56:42 +00004076 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004077 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004078
Steve Naroff4a746782008-01-09 22:43:08 +00004079 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004080 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004081#define TYPE(Class, Base)
4082#define ABSTRACT_TYPE(Class, Base)
4083#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4084#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4085#include "clang/AST/TypeNodes.def"
4086 assert(false && "Non-canonical and dependent types shouldn't get here");
4087 return QualType();
4088
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004089 case Type::LValueReference:
4090 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004091 case Type::MemberPointer:
4092 assert(false && "C++ should never be in mergeTypes");
4093 return QualType();
4094
4095 case Type::IncompleteArray:
4096 case Type::VariableArray:
4097 case Type::FunctionProto:
4098 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004099 assert(false && "Types are eliminated above");
4100 return QualType();
4101
Chris Lattner1adb8832008-01-14 05:45:46 +00004102 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004103 {
4104 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004105 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4106 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004107 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4108 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004109 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004110 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004111 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004112 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004113 return getPointerType(ResultType);
4114 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004115 case Type::BlockPointer:
4116 {
4117 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004118 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4119 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004120 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4121 if (ResultType.isNull()) return QualType();
4122 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4123 return LHS;
4124 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4125 return RHS;
4126 return getBlockPointerType(ResultType);
4127 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004128 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004129 {
4130 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4131 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4132 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4133 return QualType();
4134
4135 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4136 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4137 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4138 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004139 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4140 return LHS;
4141 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4142 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004143 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4144 ArrayType::ArraySizeModifier(), 0);
4145 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4146 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004147 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4148 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004149 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4150 return LHS;
4151 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4152 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004153 if (LVAT) {
4154 // FIXME: This isn't correct! But tricky to implement because
4155 // the array's size has to be the size of LHS, but the type
4156 // has to be different.
4157 return LHS;
4158 }
4159 if (RVAT) {
4160 // FIXME: This isn't correct! But tricky to implement because
4161 // the array's size has to be the size of RHS, but the type
4162 // has to be different.
4163 return RHS;
4164 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004165 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4166 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004167 return getIncompleteArrayType(ResultType,
4168 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004169 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004170 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004171 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004172 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004173 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004174 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004175 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004176 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004177 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004178 case Type::Complex:
4179 // Distinct complex types are incompatible.
4180 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004181 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004182 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004183 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004184 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004185 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004186 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004187 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004188 // FIXME: This should be type compatibility, e.g. whether
4189 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004190 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4191 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004192 if (LHSIface && RHSIface &&
4193 canAssignObjCInterfaces(LHSIface, RHSIface))
4194 return LHS;
4195
Eli Friedman3d815e72008-08-22 00:56:42 +00004196 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004197 }
Steve Naroff14108da2009-07-10 23:34:53 +00004198 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004199 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4200 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004201 return LHS;
4202
Steve Naroffbc76dd02008-12-10 22:14:21 +00004203 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004204 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004205 case Type::FixedWidthInt:
4206 // Distinct fixed-width integers are not compatible.
4207 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004208 case Type::TemplateSpecialization:
4209 assert(false && "Dependent types have no size");
4210 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004211 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004212
4213 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004214}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004215
Chris Lattner5426bf62008-04-07 07:01:58 +00004216//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004217// Integer Predicates
4218//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004219
Eli Friedmanad74a752008-06-28 06:23:08 +00004220unsigned ASTContext::getIntWidth(QualType T) {
4221 if (T == BoolTy)
4222 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004223 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004224 return FWIT->getWidth();
4225 }
4226 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004227 return (unsigned)getTypeSize(T);
4228}
4229
4230QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4231 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004232
4233 // Turn <4 x signed int> -> <4 x unsigned int>
4234 if (const VectorType *VTy = T->getAs<VectorType>())
4235 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4236 VTy->getNumElements());
4237
4238 // For enums, we return the unsigned version of the base type.
4239 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004240 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004241
4242 const BuiltinType *BTy = T->getAs<BuiltinType>();
4243 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004244 switch (BTy->getKind()) {
4245 case BuiltinType::Char_S:
4246 case BuiltinType::SChar:
4247 return UnsignedCharTy;
4248 case BuiltinType::Short:
4249 return UnsignedShortTy;
4250 case BuiltinType::Int:
4251 return UnsignedIntTy;
4252 case BuiltinType::Long:
4253 return UnsignedLongTy;
4254 case BuiltinType::LongLong:
4255 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004256 case BuiltinType::Int128:
4257 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004258 default:
4259 assert(0 && "Unexpected signed integer type");
4260 return QualType();
4261 }
4262}
4263
Douglas Gregor2cf26342009-04-09 22:27:44 +00004264ExternalASTSource::~ExternalASTSource() { }
4265
4266void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004267
4268
4269//===----------------------------------------------------------------------===//
4270// Builtin Type Computation
4271//===----------------------------------------------------------------------===//
4272
4273/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4274/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004275static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004276 ASTContext::GetBuiltinTypeError &Error,
4277 bool AllowTypeModifiers = true) {
4278 // Modifiers.
4279 int HowLong = 0;
4280 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004281
Chris Lattner86df27b2009-06-14 00:45:47 +00004282 // Read the modifiers first.
4283 bool Done = false;
4284 while (!Done) {
4285 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004286 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004287 case 'S':
4288 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4289 assert(!Signed && "Can't use 'S' modifier multiple times!");
4290 Signed = true;
4291 break;
4292 case 'U':
4293 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4294 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4295 Unsigned = true;
4296 break;
4297 case 'L':
4298 assert(HowLong <= 2 && "Can't have LLLL modifier");
4299 ++HowLong;
4300 break;
4301 }
4302 }
4303
4304 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Chris Lattner86df27b2009-06-14 00:45:47 +00004306 // Read the base type.
4307 switch (*Str++) {
4308 default: assert(0 && "Unknown builtin type letter!");
4309 case 'v':
4310 assert(HowLong == 0 && !Signed && !Unsigned &&
4311 "Bad modifiers used with 'v'!");
4312 Type = Context.VoidTy;
4313 break;
4314 case 'f':
4315 assert(HowLong == 0 && !Signed && !Unsigned &&
4316 "Bad modifiers used with 'f'!");
4317 Type = Context.FloatTy;
4318 break;
4319 case 'd':
4320 assert(HowLong < 2 && !Signed && !Unsigned &&
4321 "Bad modifiers used with 'd'!");
4322 if (HowLong)
4323 Type = Context.LongDoubleTy;
4324 else
4325 Type = Context.DoubleTy;
4326 break;
4327 case 's':
4328 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4329 if (Unsigned)
4330 Type = Context.UnsignedShortTy;
4331 else
4332 Type = Context.ShortTy;
4333 break;
4334 case 'i':
4335 if (HowLong == 3)
4336 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4337 else if (HowLong == 2)
4338 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4339 else if (HowLong == 1)
4340 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4341 else
4342 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4343 break;
4344 case 'c':
4345 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4346 if (Signed)
4347 Type = Context.SignedCharTy;
4348 else if (Unsigned)
4349 Type = Context.UnsignedCharTy;
4350 else
4351 Type = Context.CharTy;
4352 break;
4353 case 'b': // boolean
4354 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4355 Type = Context.BoolTy;
4356 break;
4357 case 'z': // size_t.
4358 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4359 Type = Context.getSizeType();
4360 break;
4361 case 'F':
4362 Type = Context.getCFConstantStringType();
4363 break;
4364 case 'a':
4365 Type = Context.getBuiltinVaListType();
4366 assert(!Type.isNull() && "builtin va list type not initialized!");
4367 break;
4368 case 'A':
4369 // This is a "reference" to a va_list; however, what exactly
4370 // this means depends on how va_list is defined. There are two
4371 // different kinds of va_list: ones passed by value, and ones
4372 // passed by reference. An example of a by-value va_list is
4373 // x86, where va_list is a char*. An example of by-ref va_list
4374 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4375 // we want this argument to be a char*&; for x86-64, we want
4376 // it to be a __va_list_tag*.
4377 Type = Context.getBuiltinVaListType();
4378 assert(!Type.isNull() && "builtin va list type not initialized!");
4379 if (Type->isArrayType()) {
4380 Type = Context.getArrayDecayedType(Type);
4381 } else {
4382 Type = Context.getLValueReferenceType(Type);
4383 }
4384 break;
4385 case 'V': {
4386 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004387 unsigned NumElements = strtoul(Str, &End, 10);
4388 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Chris Lattner86df27b2009-06-14 00:45:47 +00004390 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004391
Chris Lattner86df27b2009-06-14 00:45:47 +00004392 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4393 Type = Context.getVectorType(ElementType, NumElements);
4394 break;
4395 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004396 case 'X': {
4397 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4398 Type = Context.getComplexType(ElementType);
4399 break;
4400 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004401 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004402 Type = Context.getFILEType();
4403 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004404 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004405 return QualType();
4406 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004407 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004408 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004409 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004410 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004411 else
4412 Type = Context.getjmp_bufType();
4413
Mike Stumpfd612db2009-07-28 23:47:15 +00004414 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004415 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004416 return QualType();
4417 }
4418 break;
Mike Stump782fa302009-07-28 02:25:19 +00004419 }
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Chris Lattner86df27b2009-06-14 00:45:47 +00004421 if (!AllowTypeModifiers)
4422 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004423
Chris Lattner86df27b2009-06-14 00:45:47 +00004424 Done = false;
4425 while (!Done) {
4426 switch (*Str++) {
4427 default: Done = true; --Str; break;
4428 case '*':
4429 Type = Context.getPointerType(Type);
4430 break;
4431 case '&':
4432 Type = Context.getLValueReferenceType(Type);
4433 break;
4434 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4435 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004436 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004437 break;
4438 }
4439 }
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Chris Lattner86df27b2009-06-14 00:45:47 +00004441 return Type;
4442}
4443
4444/// GetBuiltinType - Return the type for the specified builtin.
4445QualType ASTContext::GetBuiltinType(unsigned id,
4446 GetBuiltinTypeError &Error) {
4447 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004448
Chris Lattner86df27b2009-06-14 00:45:47 +00004449 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Chris Lattner86df27b2009-06-14 00:45:47 +00004451 Error = GE_None;
4452 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4453 if (Error != GE_None)
4454 return QualType();
4455 while (TypeStr[0] && TypeStr[0] != '.') {
4456 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4457 if (Error != GE_None)
4458 return QualType();
4459
4460 // Do array -> pointer decay. The builtin should use the decayed type.
4461 if (Ty->isArrayType())
4462 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Chris Lattner86df27b2009-06-14 00:45:47 +00004464 ArgTypes.push_back(Ty);
4465 }
4466
4467 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4468 "'.' should only occur at end of builtin type list!");
4469
4470 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4471 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4472 return getFunctionNoProtoType(ResType);
4473 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4474 TypeStr[0] == '.', 0);
4475}
Eli Friedmana95d7572009-08-19 07:44:53 +00004476
4477QualType
4478ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4479 // Perform the usual unary conversions. We do this early so that
4480 // integral promotions to "int" can allow us to exit early, in the
4481 // lhs == rhs check. Also, for conversion purposes, we ignore any
4482 // qualifiers. For example, "const float" and "float" are
4483 // equivalent.
4484 if (lhs->isPromotableIntegerType())
4485 lhs = getPromotedIntegerType(lhs);
4486 else
4487 lhs = lhs.getUnqualifiedType();
4488 if (rhs->isPromotableIntegerType())
4489 rhs = getPromotedIntegerType(rhs);
4490 else
4491 rhs = rhs.getUnqualifiedType();
4492
4493 // If both types are identical, no conversion is needed.
4494 if (lhs == rhs)
4495 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004496
Eli Friedmana95d7572009-08-19 07:44:53 +00004497 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4498 // The caller can deal with this (e.g. pointer + int).
4499 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4500 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004501
4502 // At this point, we have two different arithmetic types.
4503
Eli Friedmana95d7572009-08-19 07:44:53 +00004504 // Handle complex types first (C99 6.3.1.8p1).
4505 if (lhs->isComplexType() || rhs->isComplexType()) {
4506 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004507 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004508 // convert the rhs to the lhs complex type.
4509 return lhs;
4510 }
Mike Stump1eb44332009-09-09 15:08:12 +00004511 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004512 // convert the lhs to the rhs complex type.
4513 return rhs;
4514 }
4515 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004516 // When both operands are complex, the shorter operand is converted to the
4517 // type of the longer, and that is the type of the result. This corresponds
4518 // to what is done when combining two real floating-point operands.
4519 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004520 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004521 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004522 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004523 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004524 // "double _Complex" is promoted to "long double _Complex".
4525 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004526
4527 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004528 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004529 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004530 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004531 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004532 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4533 // domains match. This is a requirement for our implementation, C99
4534 // does not require this promotion.
4535 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4536 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4537 return rhs;
4538 } else { // handle "_Complex double, double".
4539 return lhs;
4540 }
4541 }
4542 return lhs; // The domain/size match exactly.
4543 }
4544 // Now handle "real" floating types (i.e. float, double, long double).
4545 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4546 // if we have an integer operand, the result is the real floating type.
4547 if (rhs->isIntegerType()) {
4548 // convert rhs to the lhs floating point type.
4549 return lhs;
4550 }
4551 if (rhs->isComplexIntegerType()) {
4552 // convert rhs to the complex floating point type.
4553 return getComplexType(lhs);
4554 }
4555 if (lhs->isIntegerType()) {
4556 // convert lhs to the rhs floating point type.
4557 return rhs;
4558 }
Mike Stump1eb44332009-09-09 15:08:12 +00004559 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004560 // convert lhs to the complex floating point type.
4561 return getComplexType(rhs);
4562 }
4563 // We have two real floating types, float/complex combos were handled above.
4564 // Convert the smaller operand to the bigger result.
4565 int result = getFloatingTypeOrder(lhs, rhs);
4566 if (result > 0) // convert the rhs
4567 return lhs;
4568 assert(result < 0 && "illegal float comparison");
4569 return rhs; // convert the lhs
4570 }
4571 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4572 // Handle GCC complex int extension.
4573 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4574 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4575
4576 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004577 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004578 rhsComplexInt->getElementType()) >= 0)
4579 return lhs; // convert the rhs
4580 return rhs;
4581 } else if (lhsComplexInt && rhs->isIntegerType()) {
4582 // convert the rhs to the lhs complex type.
4583 return lhs;
4584 } else if (rhsComplexInt && lhs->isIntegerType()) {
4585 // convert the lhs to the rhs complex type.
4586 return rhs;
4587 }
4588 }
4589 // Finally, we have two differing integer types.
4590 // The rules for this case are in C99 6.3.1.8
4591 int compare = getIntegerTypeOrder(lhs, rhs);
4592 bool lhsSigned = lhs->isSignedIntegerType(),
4593 rhsSigned = rhs->isSignedIntegerType();
4594 QualType destType;
4595 if (lhsSigned == rhsSigned) {
4596 // Same signedness; use the higher-ranked type
4597 destType = compare >= 0 ? lhs : rhs;
4598 } else if (compare != (lhsSigned ? 1 : -1)) {
4599 // The unsigned type has greater than or equal rank to the
4600 // signed type, so use the unsigned type
4601 destType = lhsSigned ? rhs : lhs;
4602 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4603 // The two types are different widths; if we are here, that
4604 // means the signed type is larger than the unsigned type, so
4605 // use the signed type.
4606 destType = lhsSigned ? lhs : rhs;
4607 } else {
4608 // The signed type is higher-ranked than the unsigned type,
4609 // but isn't actually any bigger (like unsigned int and long
4610 // on most 32-bit systems). Use the unsigned type corresponding
4611 // to the signed type.
4612 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4613 }
4614 return destType;
4615}