blob: e091bf10b62977265f3189fdc4cbfd6c6ffb5427 [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"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +000062
63 // Release all of the memory associated with overridden C++ methods.
64 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
65 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
66 OM != OMEnd; ++OM)
67 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +000068
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000069 if (FreeMemory) {
70 // Deallocate all the types.
71 while (!Types.empty()) {
72 Types.back()->Destroy(*this);
73 Types.pop_back();
74 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000075
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000076 for (llvm::FoldingSet<ExtQuals>::iterator
77 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
78 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000079 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000080 }
81 }
82
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000083 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
84 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
85 // Increment in loop to prevent using deallocated memory.
86 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
87 delete R;
88 }
89
90 for (llvm::DenseMap<const ObjCContainerDecl*,
91 const ASTRecordLayout*>::iterator
92 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
93 // Increment in loop to prevent using deallocated memory.
94 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
95 delete R;
Nuno Lopesb74668e2008-12-17 22:30:25 +000096 }
97
Douglas Gregorab452ba2009-03-26 23:50:42 +000098 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000099 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
100 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000101 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000102 NNS != NNSEnd; ) {
103 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000104 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000105 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000106
107 if (GlobalNestedNameSpecifier)
108 GlobalNestedNameSpecifier->Destroy(*this);
109
Eli Friedmanb26153c2008-05-27 03:08:09 +0000110 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000111}
112
Mike Stump1eb44332009-09-09 15:08:12 +0000113void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000114ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
115 ExternalSource.reset(Source.take());
116}
117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118void ASTContext::PrintStats() const {
119 fprintf(stderr, "*** AST Context Stats:\n");
120 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000121
Douglas Gregordbe833d2009-05-26 14:40:08 +0000122 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000123#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124#define ABSTRACT_TYPE(Name, Parent)
125#include "clang/AST/TypeNodes.def"
126 0 // Extra
127 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
130 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000131 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 unsigned Idx = 0;
135 unsigned TotalBytes = 0;
136#define TYPE(Name, Parent) \
137 if (counts[Idx]) \
138 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
139 TotalBytes += counts[Idx] * sizeof(Name##Type); \
140 ++Idx;
141#define ABSTRACT_TYPE(Name, Parent)
142#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Douglas Gregordbe833d2009-05-26 14:40:08 +0000144 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000145
146 if (ExternalSource.get()) {
147 fprintf(stderr, "\n");
148 ExternalSource->PrintStats();
149 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000150}
151
152
John McCalle27ec8a2009-10-23 23:03:21 +0000153void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000154 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000155 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000156 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000157}
158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159void ASTContext::InitBuiltinTypes() {
160 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 // C99 6.2.5p19.
163 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 // C99 6.2.5p2.
166 InitBuiltinType(BoolTy, BuiltinType::Bool);
167 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000168 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 InitBuiltinType(CharTy, BuiltinType::Char_S);
170 else
171 InitBuiltinType(CharTy, BuiltinType::Char_U);
172 // C99 6.2.5p4.
173 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
174 InitBuiltinType(ShortTy, BuiltinType::Short);
175 InitBuiltinType(IntTy, BuiltinType::Int);
176 InitBuiltinType(LongTy, BuiltinType::Long);
177 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // C99 6.2.5p6.
180 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
181 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
182 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
183 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
184 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // C99 6.2.5p10.
187 InitBuiltinType(FloatTy, BuiltinType::Float);
188 InitBuiltinType(DoubleTy, BuiltinType::Double);
189 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000190
Chris Lattner2df9ced2009-04-30 02:43:43 +0000191 // GNU extension, 128-bit integers.
192 InitBuiltinType(Int128Ty, BuiltinType::Int128);
193 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
194
Chris Lattner3a250322009-02-26 23:43:47 +0000195 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
196 InitBuiltinType(WCharTy, BuiltinType::WChar);
197 else // C99
198 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000199
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000200 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
201 InitBuiltinType(Char16Ty, BuiltinType::Char16);
202 else // C99
203 Char16Ty = getFromTargetType(Target.getChar16Type());
204
205 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
206 InitBuiltinType(Char32Ty, BuiltinType::Char32);
207 else // C99
208 Char32Ty = getFromTargetType(Target.getChar32Type());
209
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000211 InitBuiltinType(OverloadTy, BuiltinType::Overload);
212
213 // Placeholder type for type-dependent expressions whose type is
214 // completely unknown. No code should ever check a type against
215 // DependentTy and users should never see it; however, it is here to
216 // help diagnose failures to properly check for type-dependent
217 // expressions.
218 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219
Mike Stump1eb44332009-09-09 15:08:12 +0000220 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000221 // not yet been deduced.
222 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 // C99 6.2.5p11.
225 FloatComplexTy = getComplexType(FloatTy);
226 DoubleComplexTy = getComplexType(DoubleTy);
227 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228
Steve Naroff7e219e42007-10-15 14:41:52 +0000229 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Steve Naroffde2e22d2009-07-15 18:40:39 +0000231 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
232 ObjCIdTypedefType = QualType();
233 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000234 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000236 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000237 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
238 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000239 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000240
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000241 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000243 // void * type
244 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000245
246 // nullptr type (C++0x 2.14.7)
247 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000248}
249
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000250MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000251ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000252 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000253 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 = InstantiatedFromStaticDataMember.find(Var);
255 if (Pos == InstantiatedFromStaticDataMember.end())
256 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Douglas Gregor7caa6822009-07-24 20:34:43 +0000258 return Pos->second;
259}
260
Mike Stump1eb44332009-09-09 15:08:12 +0000261void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000262ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
263 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000264 assert(Inst->isStaticDataMember() && "Not a static data member");
265 assert(Tmpl->isStaticDataMember() && "Not a static data member");
266 assert(!InstantiatedFromStaticDataMember[Inst] &&
267 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000268 InstantiatedFromStaticDataMember[Inst]
269 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000270}
271
John McCall7ba107a2009-11-18 02:36:19 +0000272NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000273ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000274 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000275 = InstantiatedFromUsingDecl.find(UUD);
276 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000277 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Anders Carlsson0d8df782009-08-29 19:37:28 +0000279 return Pos->second;
280}
281
282void
John McCalled976492009-12-04 22:46:56 +0000283ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
284 assert((isa<UsingDecl>(Pattern) ||
285 isa<UnresolvedUsingValueDecl>(Pattern) ||
286 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
287 "pattern decl is not a using decl");
288 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
289 InstantiatedFromUsingDecl[Inst] = Pattern;
290}
291
292UsingShadowDecl *
293ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
294 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
295 = InstantiatedFromUsingShadowDecl.find(Inst);
296 if (Pos == InstantiatedFromUsingShadowDecl.end())
297 return 0;
298
299 return Pos->second;
300}
301
302void
303ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
304 UsingShadowDecl *Pattern) {
305 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
306 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000307}
308
Anders Carlssond8b285f2009-09-01 04:26:58 +0000309FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
310 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
311 = InstantiatedFromUnnamedFieldDecl.find(Field);
312 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
313 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 return Pos->second;
316}
317
318void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
319 FieldDecl *Tmpl) {
320 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
321 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
322 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
323 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlssond8b285f2009-09-01 04:26:58 +0000325 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
326}
327
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000328CXXMethodVector::iterator CXXMethodVector::begin() const {
329 if ((Storage & 0x01) == 0)
330 return reinterpret_cast<iterator>(&Storage);
331
332 vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
333 return &Vec->front();
334}
335
336CXXMethodVector::iterator CXXMethodVector::end() const {
337 if ((Storage & 0x01) == 0) {
338 if (Storage == 0)
339 return reinterpret_cast<iterator>(&Storage);
340
341 return reinterpret_cast<iterator>(&Storage) + 1;
342 }
343
344 vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
345 return &Vec->front() + Vec->size();
346}
347
348void CXXMethodVector::push_back(const CXXMethodDecl *Method) {
349 if (Storage == 0) {
350 // 0 -> 1 element.
351 Storage = reinterpret_cast<uintptr_t>(Method);
352 return;
353 }
354
355 vector_type *Vec;
356 if ((Storage & 0x01) == 0) {
357 // 1 -> 2 elements. Allocate a new vector and push the element into that
358 // vector.
359 Vec = new vector_type;
360 Vec->push_back(reinterpret_cast<const CXXMethodDecl *>(Storage));
361 Storage = reinterpret_cast<uintptr_t>(Vec) | 0x01;
362 } else
363 Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
364
365 // Add the new method to the vector.
366 Vec->push_back(Method);
367}
368
369void CXXMethodVector::Destroy() {
370 if (Storage & 0x01)
371 delete reinterpret_cast<vector_type *>(Storage & ~0x01);
372
373 Storage = 0;
374}
375
376
377ASTContext::overridden_cxx_method_iterator
378ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
379 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
380 = OverriddenMethods.find(Method);
381 if (Pos == OverriddenMethods.end())
382 return 0;
383
384 return Pos->second.begin();
385}
386
387ASTContext::overridden_cxx_method_iterator
388ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
389 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
390 = OverriddenMethods.find(Method);
391 if (Pos == OverriddenMethods.end())
392 return 0;
393
394 return Pos->second.end();
395}
396
397void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
398 const CXXMethodDecl *Overridden) {
399 OverriddenMethods[Method].push_back(Overridden);
400}
401
Douglas Gregor2e222532009-07-02 17:08:52 +0000402namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000403 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000404 : std::binary_function<SourceRange, SourceRange, bool> {
405 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregor2e222532009-07-02 17:08:52 +0000407 public:
408 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 bool operator()(SourceRange X, SourceRange Y) {
411 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
412 }
413 };
414}
415
416/// \brief Determine whether the given comment is a Doxygen-style comment.
417///
418/// \param Start the start of the comment text.
419///
420/// \param End the end of the comment text.
421///
422/// \param Member whether we want to check whether this is a member comment
423/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
424/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000425static bool
426isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000427 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000428 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000429 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
430 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
431 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Douglas Gregor2e222532009-07-02 17:08:52 +0000433 if (End - Start < 4)
434 return false;
435
436 assert(Start[0] == '/' && "Not a comment?");
437 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
438 return false;
439 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
440 return false;
441
442 return (Start[3] == '<') == Member;
443}
444
445/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000446/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000447const char *ASTContext::getCommentForDecl(const Decl *D) {
448 if (!D)
449 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 // Check whether we have cached a comment string for this declaration
452 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000453 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 = DeclComments.find(D);
455 if (Pos != DeclComments.end())
456 return Pos->second.c_str();
457
Mike Stump1eb44332009-09-09 15:08:12 +0000458 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000459 // that source, do so now.
460 if (ExternalSource && !LoadedExternalComments) {
461 std::vector<SourceRange> LoadedComments;
462 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Douglas Gregor2e222532009-07-02 17:08:52 +0000464 if (!LoadedComments.empty())
465 Comments.insert(Comments.begin(), LoadedComments.begin(),
466 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Douglas Gregor2e222532009-07-02 17:08:52 +0000468 LoadedExternalComments = true;
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
471 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000472 if (Comments.empty())
473 return 0;
474
475 // If the declaration doesn't map directly to a location in a file, we
476 // can't find the comment.
477 SourceLocation DeclStartLoc = D->getLocStart();
478 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
479 return 0;
480
481 // Find the comment that occurs just before this declaration.
482 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000483 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000484 SourceRange(DeclStartLoc),
485 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Douglas Gregor2e222532009-07-02 17:08:52 +0000487 // Decompose the location for the start of the declaration and find the
488 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000489 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000490 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000491 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 // First check whether we have a comment for a member.
495 if (LastComment != Comments.end() &&
496 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
497 isDoxygenComment(SourceMgr, *LastComment, true)) {
498 std::pair<FileID, unsigned> LastCommentEndDecomp
499 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
500 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
501 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000502 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000503 LastCommentEndDecomp.second)) {
504 // The Doxygen member comment comes after the declaration starts and
505 // is on the same line and in the same file as the declaration. This
506 // is the comment we want.
507 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000508 Result.append(FileBufferStart +
509 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000510 FileBufferStart + LastCommentEndDecomp.second + 1);
511 return Result.c_str();
512 }
513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 if (LastComment == Comments.begin())
516 return 0;
517 --LastComment;
518
519 // Decompose the end of the comment.
520 std::pair<FileID, unsigned> LastCommentEndDecomp
521 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Douglas Gregor2e222532009-07-02 17:08:52 +0000523 // If the comment and the declaration aren't in the same file, then they
524 // aren't related.
525 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
526 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Douglas Gregor2e222532009-07-02 17:08:52 +0000528 // Check that we actually have a Doxygen comment.
529 if (!isDoxygenComment(SourceMgr, *LastComment))
530 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor2e222532009-07-02 17:08:52 +0000532 // Compute the starting line for the declaration and for the end of the
533 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000534 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000535 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
536 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000537 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000538 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor2e222532009-07-02 17:08:52 +0000540 // If the comment does not end on the line prior to the declaration, then
541 // the comment is not associated with the declaration at all.
542 if (CommentEndLine + 1 != DeclStartLine)
543 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Douglas Gregor2e222532009-07-02 17:08:52 +0000545 // We have a comment, but there may be more comments on the previous lines.
546 // Keep looking so long as the comments are still Doxygen comments and are
547 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000548 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000549 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
550 std::vector<SourceRange>::iterator FirstComment = LastComment;
551 while (FirstComment != Comments.begin()) {
552 // Look at the previous comment
553 --FirstComment;
554 std::pair<FileID, unsigned> Decomp
555 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregor2e222532009-07-02 17:08:52 +0000557 // If this previous comment is in a different file, we're done.
558 if (Decomp.first != DeclStartDecomp.first) {
559 ++FirstComment;
560 break;
561 }
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregor2e222532009-07-02 17:08:52 +0000563 // If this comment is not a Doxygen comment, we're done.
564 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
565 ++FirstComment;
566 break;
567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Douglas Gregor2e222532009-07-02 17:08:52 +0000569 // If the line number is not what we expected, we're done.
570 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
571 if (Line != ExpectedLine) {
572 ++FirstComment;
573 break;
574 }
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor2e222532009-07-02 17:08:52 +0000576 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000577 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000578 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
579 }
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Douglas Gregor2e222532009-07-02 17:08:52 +0000581 // The iterator range [FirstComment, LastComment] contains all of the
582 // BCPL comments that, together, are associated with this declaration.
583 // Form a single comment block string for this declaration that concatenates
584 // all of these comments.
585 std::string &Result = DeclComments[D];
586 while (FirstComment != LastComment) {
587 std::pair<FileID, unsigned> DecompStart
588 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
589 std::pair<FileID, unsigned> DecompEnd
590 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
591 Result.append(FileBufferStart + DecompStart.second,
592 FileBufferStart + DecompEnd.second + 1);
593 ++FirstComment;
594 }
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2e222532009-07-02 17:08:52 +0000596 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000597 Result.append(FileBufferStart +
598 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000599 FileBufferStart + LastCommentEndDecomp.second + 1);
600 return Result.c_str();
601}
602
Chris Lattner464175b2007-07-18 17:52:12 +0000603//===----------------------------------------------------------------------===//
604// Type Sizing and Analysis
605//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000606
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000607/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
608/// scalar floating point type.
609const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000610 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000611 assert(BT && "Not a floating point type!");
612 switch (BT->getKind()) {
613 default: assert(0 && "Not a floating point type!");
614 case BuiltinType::Float: return Target.getFloatFormat();
615 case BuiltinType::Double: return Target.getDoubleFormat();
616 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
617 }
618}
619
Ken Dyck8b752f12010-01-27 17:10:57 +0000620/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000621/// specified decl. Note that bitfields do not have a valid alignment, so
622/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000623/// If @p RefAsPointee, references are treated like their underlying type
624/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000625CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000626 unsigned Align = Target.getCharWidth();
627
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000628 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000629 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000630
Chris Lattneraf707ab2009-01-24 21:53:27 +0000631 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
632 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000633 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000634 if (RefAsPointee)
635 T = RT->getPointeeType();
636 else
637 T = getPointerType(RT->getPointeeType());
638 }
639 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000640 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000641 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
642 T = cast<ArrayType>(T)->getElementType();
643
644 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
645 }
Charles Davis05f62472010-02-23 04:52:00 +0000646 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
647 // In the case of a field in a packed struct, we want the minimum
648 // of the alignment of the field and the alignment of the struct.
649 Align = std::min(Align,
650 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
651 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000652 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000653
Ken Dyck8b752f12010-01-27 17:10:57 +0000654 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000655}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000656
Chris Lattnera7674d82007-07-13 22:13:22 +0000657/// getTypeSize - Return the size of the specified type, in bits. This method
658/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000659///
660/// FIXME: Pointers into different addr spaces could have different sizes and
661/// alignment requirements: getPointerInfo should take an AddrSpace, this
662/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000663std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000664ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000665 uint64_t Width=0;
666 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000667 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000668#define TYPE(Class, Base)
669#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000670#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
672#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000673 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000674 break;
675
Chris Lattner692233e2007-07-13 22:27:08 +0000676 case Type::FunctionNoProto:
677 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000678 // GCC extension: alignof(function) = 32 bits
679 Width = 0;
680 Align = 32;
681 break;
682
Douglas Gregor72564e72009-02-26 23:50:07 +0000683 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000684 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000685 Width = 0;
686 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
687 break;
688
Steve Narofffb22d962007-08-30 01:06:46 +0000689 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000690 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner98be4942008-03-05 18:54:05 +0000692 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000693 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000694 Align = EltInfo.second;
695 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000696 }
Nate Begeman213541a2008-04-18 23:10:10 +0000697 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000698 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000699 const VectorType *VT = cast<VectorType>(T);
700 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
701 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000702 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000703 // If the alignment is not a power of 2, round up to the next power of 2.
704 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000705 if (VT->getNumElements() & (VT->getNumElements()-1)) {
706 Align = llvm::NextPowerOf2(Align);
707 Width = llvm::RoundUpToAlignment(Width, Align);
708 }
Chris Lattner030d8842007-07-19 22:06:24 +0000709 break;
710 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000711
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000712 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000713 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000714 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000715 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000716 // GCC extension: alignof(void) = 8 bits.
717 Width = 0;
718 Align = 8;
719 break;
720
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000721 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000722 Width = Target.getBoolWidth();
723 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000724 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000725 case BuiltinType::Char_S:
726 case BuiltinType::Char_U:
727 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000728 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000729 Width = Target.getCharWidth();
730 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000731 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000732 case BuiltinType::WChar:
733 Width = Target.getWCharWidth();
734 Align = Target.getWCharAlign();
735 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000736 case BuiltinType::Char16:
737 Width = Target.getChar16Width();
738 Align = Target.getChar16Align();
739 break;
740 case BuiltinType::Char32:
741 Width = Target.getChar32Width();
742 Align = Target.getChar32Align();
743 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000744 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000745 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000746 Width = Target.getShortWidth();
747 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000748 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000749 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000750 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000751 Width = Target.getIntWidth();
752 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000753 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000754 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000755 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000756 Width = Target.getLongWidth();
757 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000758 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000759 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000760 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000761 Width = Target.getLongLongWidth();
762 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000763 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000764 case BuiltinType::Int128:
765 case BuiltinType::UInt128:
766 Width = 128;
767 Align = 128; // int128_t is 128-bit aligned on all targets.
768 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000769 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000770 Width = Target.getFloatWidth();
771 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000772 break;
773 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000774 Width = Target.getDoubleWidth();
775 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000776 break;
777 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000778 Width = Target.getLongDoubleWidth();
779 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000780 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000781 case BuiltinType::NullPtr:
782 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
783 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000784 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000785 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000786 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000787 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000788 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000789 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000790 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000791 case Type::BlockPointer: {
792 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
793 Width = Target.getPointerWidth(AS);
794 Align = Target.getPointerAlign(AS);
795 break;
796 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000797 case Type::LValueReference:
798 case Type::RValueReference: {
799 // alignof and sizeof should never enter this code path here, so we go
800 // the pointer route.
801 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
802 Width = Target.getPointerWidth(AS);
803 Align = Target.getPointerAlign(AS);
804 break;
805 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000806 case Type::Pointer: {
807 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000808 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000809 Align = Target.getPointerAlign(AS);
810 break;
811 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000812 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000813 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000814 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000815 getTypeInfo(getPointerDiffType());
816 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000817 if (Pointee->isFunctionType())
818 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000819 Align = PtrDiffInfo.second;
820 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000821 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000822 case Type::Complex: {
823 // Complex types have the same alignment as their elements, but twice the
824 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000825 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000826 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000827 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000828 Align = EltInfo.second;
829 break;
830 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000831 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000832 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000833 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
834 Width = Layout.getSize();
835 Align = Layout.getAlignment();
836 break;
837 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000838 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000839 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000840 const TagType *TT = cast<TagType>(T);
841
842 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000843 Width = 1;
844 Align = 1;
845 break;
846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Daniel Dunbar1d751182008-11-08 05:48:37 +0000848 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000849 return getTypeInfo(ET->getDecl()->getIntegerType());
850
Daniel Dunbar1d751182008-11-08 05:48:37 +0000851 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000852 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
853 Width = Layout.getSize();
854 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000855 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000856 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000857
Chris Lattner9fcfe922009-10-22 05:17:15 +0000858 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000859 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
860 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000861
Chris Lattner9fcfe922009-10-22 05:17:15 +0000862 case Type::Elaborated:
863 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
864 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000865
Douglas Gregor18857642009-04-30 17:32:17 +0000866 case Type::Typedef: {
867 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000868 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000869 Align = std::max(Aligned->getMaxAlignment(),
870 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000871 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
872 } else
873 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000874 break;
Chris Lattner71763312008-04-06 22:05:18 +0000875 }
Douglas Gregor18857642009-04-30 17:32:17 +0000876
877 case Type::TypeOfExpr:
878 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
879 .getTypePtr());
880
881 case Type::TypeOf:
882 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
883
Anders Carlsson395b4752009-06-24 19:06:50 +0000884 case Type::Decltype:
885 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
886 .getTypePtr());
887
Douglas Gregor18857642009-04-30 17:32:17 +0000888 case Type::QualifiedName:
889 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Douglas Gregor18857642009-04-30 17:32:17 +0000891 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000892 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000893 "Cannot request the size of a dependent type");
894 // FIXME: this is likely to be wrong once we support template
895 // aliases, since a template alias could refer to a typedef that
896 // has an __aligned__ attribute on it.
897 return getTypeInfo(getCanonicalType(T));
898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner464175b2007-07-18 17:52:12 +0000900 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000901 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000902}
903
Ken Dyckbdc601b2009-12-22 14:23:30 +0000904/// getTypeSizeInChars - Return the size of the specified type, in characters.
905/// This method does not work on incomplete types.
906CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000907 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000908}
909CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000910 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000911}
912
Ken Dyck16e20cc2010-01-26 17:25:18 +0000913/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000914/// characters. This method does not work on incomplete types.
915CharUnits ASTContext::getTypeAlignInChars(QualType T) {
916 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
917}
918CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
919 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
920}
921
Chris Lattner34ebde42009-01-27 18:08:34 +0000922/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
923/// type for the current target in bits. This can be different than the ABI
924/// alignment in cases where it is beneficial for performance to overalign
925/// a data type.
926unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
927 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000928
929 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000930 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000931 T = CT->getElementType().getTypePtr();
932 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
933 T->isSpecificBuiltinType(BuiltinType::LongLong))
934 return std::max(ABIAlign, (unsigned)getTypeSize(T));
935
Chris Lattner34ebde42009-01-27 18:08:34 +0000936 return ABIAlign;
937}
938
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000939static void CollectLocalObjCIvars(ASTContext *Ctx,
940 const ObjCInterfaceDecl *OI,
941 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000942 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
943 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000944 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000945 if (!IVDecl->isInvalidDecl())
946 Fields.push_back(cast<FieldDecl>(IVDecl));
947 }
948}
949
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000950void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
951 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
952 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
953 CollectObjCIvars(SuperClass, Fields);
954 CollectLocalObjCIvars(this, OI, Fields);
955}
956
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000957/// ShallowCollectObjCIvars -
958/// Collect all ivars, including those synthesized, in the current class.
959///
960void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000961 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000962 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
963 E = OI->ivar_end(); I != E; ++I) {
964 Ivars.push_back(*I);
965 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000966
967 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000968}
969
Fariborz Jahanian98200742009-05-12 18:14:29 +0000970void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
971 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000972 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
973 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000974 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
975 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Fariborz Jahanian98200742009-05-12 18:14:29 +0000977 // Also look into nested protocols.
978 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
979 E = PD->protocol_end(); P != E; ++P)
980 CollectProtocolSynthesizedIvars(*P, Ivars);
981}
982
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000983/// CollectNonClassIvars -
984/// This routine collects all other ivars which are not declared in the class.
985/// This includes synthesized ivars and those in class's implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000986///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000987void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000988 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000989 // Find ivars declared in class extension.
990 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
991 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
992 E = CDecl->ivar_end(); I != E; ++I) {
993 Ivars.push_back(*I);
994 }
995 }
996
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000997 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
998 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000999 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
1000 Ivars.push_back(Ivar);
1001 }
1002 // Also look into interface's protocol list for properties declared
1003 // in the protocol and whose ivars are synthesized.
1004 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1005 PE = OI->protocol_end(); P != PE; ++P) {
1006 ObjCProtocolDecl *PD = (*P);
1007 CollectProtocolSynthesizedIvars(PD, Ivars);
1008 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001009
1010 // Also add any ivar defined in this class's implementation
1011 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1012 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1013 E = ImplDecl->ivar_end(); I != E; ++I)
1014 Ivars.push_back(*I);
1015 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001016}
1017
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001018/// CollectInheritedProtocols - Collect all protocols in current class and
1019/// those inherited by it.
1020void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001021 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001022 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1023 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1024 PE = OI->protocol_end(); P != PE; ++P) {
1025 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001026 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001027 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001028 PE = Proto->protocol_end(); P != PE; ++P) {
1029 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001030 CollectInheritedProtocols(*P, Protocols);
1031 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001032 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001033
1034 // Categories of this Interface.
1035 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1036 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1037 CollectInheritedProtocols(CDeclChain, Protocols);
1038 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1039 while (SD) {
1040 CollectInheritedProtocols(SD, Protocols);
1041 SD = SD->getSuperClass();
1042 }
1043 return;
1044 }
1045 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1046 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1047 PE = OC->protocol_end(); P != PE; ++P) {
1048 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001049 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001050 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1051 PE = Proto->protocol_end(); P != PE; ++P)
1052 CollectInheritedProtocols(*P, Protocols);
1053 }
1054 return;
1055 }
1056 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1057 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1058 PE = OP->protocol_end(); P != PE; ++P) {
1059 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001060 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001061 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1062 PE = Proto->protocol_end(); P != PE; ++P)
1063 CollectInheritedProtocols(*P, Protocols);
1064 }
1065 return;
1066 }
1067}
1068
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001069unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1070 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001071 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1072 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001073 if ((*I)->getPropertyIvarDecl())
1074 ++count;
1075
1076 // Also look into nested protocols.
1077 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1078 E = PD->protocol_end(); P != E; ++P)
1079 count += CountProtocolSynthesizedIvars(*P);
1080 return count;
1081}
1082
Mike Stump1eb44332009-09-09 15:08:12 +00001083unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001084 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001085 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1086 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001087 if ((*I)->getPropertyIvarDecl())
1088 ++count;
1089 }
1090 // Also look into interface's protocol list for properties declared
1091 // in the protocol and whose ivars are synthesized.
1092 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1093 PE = OI->protocol_end(); P != PE; ++P) {
1094 ObjCProtocolDecl *PD = (*P);
1095 count += CountProtocolSynthesizedIvars(PD);
1096 }
1097 return count;
1098}
1099
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001100/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1101ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1102 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1103 I = ObjCImpls.find(D);
1104 if (I != ObjCImpls.end())
1105 return cast<ObjCImplementationDecl>(I->second);
1106 return 0;
1107}
1108/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1109ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1110 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1111 I = ObjCImpls.find(D);
1112 if (I != ObjCImpls.end())
1113 return cast<ObjCCategoryImplDecl>(I->second);
1114 return 0;
1115}
1116
1117/// \brief Set the implementation of ObjCInterfaceDecl.
1118void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1119 ObjCImplementationDecl *ImplD) {
1120 assert(IFaceD && ImplD && "Passed null params");
1121 ObjCImpls[IFaceD] = ImplD;
1122}
1123/// \brief Set the implementation of ObjCCategoryDecl.
1124void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1125 ObjCCategoryImplDecl *ImplD) {
1126 assert(CatD && ImplD && "Passed null params");
1127 ObjCImpls[CatD] = ImplD;
1128}
1129
John McCalla93c9342009-12-07 02:54:59 +00001130/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001131///
John McCalla93c9342009-12-07 02:54:59 +00001132/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001133/// the TypeLoc wrappers.
1134///
1135/// \param T the type that will be the basis for type source info. This type
1136/// should refer to how the declarator was written in source code, not to
1137/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001138TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001139 unsigned DataSize) {
1140 if (!DataSize)
1141 DataSize = TypeLoc::getFullDataSizeForType(T);
1142 else
1143 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001144 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001145
John McCalla93c9342009-12-07 02:54:59 +00001146 TypeSourceInfo *TInfo =
1147 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1148 new (TInfo) TypeSourceInfo(T);
1149 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001150}
1151
John McCalla93c9342009-12-07 02:54:59 +00001152TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001153 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001154 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001155 DI->getTypeLoc().initialize(L);
1156 return DI;
1157}
1158
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001159/// getInterfaceLayoutImpl - Get or compute information about the
1160/// layout of the given interface.
1161///
1162/// \param Impl - If given, also include the layout of the interface's
1163/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001164const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001165ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1166 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001167 assert(!D->isForwardDecl() && "Invalid interface decl!");
1168
Devang Patel44a3dde2008-06-04 21:54:36 +00001169 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001170 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001171 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1172 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1173 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001174
Daniel Dunbar453addb2009-05-03 11:16:44 +00001175 // Add in synthesized ivar count if laying out an implementation.
1176 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001177 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001178 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001179 // entry. Note we can't cache this because we simply free all
1180 // entries later; however we shouldn't look up implementations
1181 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001182 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001183 return getObjCLayout(D, 0);
1184 }
1185
Mike Stump1eb44332009-09-09 15:08:12 +00001186 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001187 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1188 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Devang Patel44a3dde2008-06-04 21:54:36 +00001190 return *NewEntry;
1191}
1192
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001193const ASTRecordLayout &
1194ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1195 return getObjCLayout(D, 0);
1196}
1197
1198const ASTRecordLayout &
1199ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1200 return getObjCLayout(D->getClassInterface(), D);
1201}
1202
Devang Patel88a981b2007-11-01 19:11:01 +00001203/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001204/// specified record (struct/union/class), which indicates its size and field
1205/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001206const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001207 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001208 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001209
Chris Lattner464175b2007-07-18 17:52:12 +00001210 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001211 // Note that we can't save a reference to the entry because this function
1212 // is recursive.
1213 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001214 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001215
Mike Stump1eb44332009-09-09 15:08:12 +00001216 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001217 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001218 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner5d2a6302007-07-18 18:26:58 +00001220 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001221}
1222
Anders Carlssonf53df232009-12-07 04:35:11 +00001223const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001224 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001225 assert(RD && "Cannot get key function for forward declarations!");
1226
1227 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1228 if (!Entry)
1229 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1230 else
1231 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1232 "Key function changed!");
1233
1234 return Entry;
1235}
1236
Chris Lattnera7674d82007-07-13 22:13:22 +00001237//===----------------------------------------------------------------------===//
1238// Type creation/memoization methods
1239//===----------------------------------------------------------------------===//
1240
John McCall0953e762009-09-24 19:53:00 +00001241QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1242 unsigned Fast = Quals.getFastQualifiers();
1243 Quals.removeFastQualifiers();
1244
1245 // Check if we've already instantiated this type.
1246 llvm::FoldingSetNodeID ID;
1247 ExtQuals::Profile(ID, TypeNode, Quals);
1248 void *InsertPos = 0;
1249 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1250 assert(EQ->getQualifiers() == Quals);
1251 QualType T = QualType(EQ, Fast);
1252 return T;
1253 }
1254
John McCall6b304a02009-09-24 23:30:46 +00001255 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001256 ExtQualNodes.InsertNode(New, InsertPos);
1257 QualType T = QualType(New, Fast);
1258 return T;
1259}
1260
1261QualType ASTContext::getVolatileType(QualType T) {
1262 QualType CanT = getCanonicalType(T);
1263 if (CanT.isVolatileQualified()) return T;
1264
1265 QualifierCollector Quals;
1266 const Type *TypeNode = Quals.strip(T);
1267 Quals.addVolatile();
1268
1269 return getExtQualType(TypeNode, Quals);
1270}
1271
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001272QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001273 QualType CanT = getCanonicalType(T);
1274 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001275 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001276
John McCall0953e762009-09-24 19:53:00 +00001277 // If we are composing extended qualifiers together, merge together
1278 // into one ExtQuals node.
1279 QualifierCollector Quals;
1280 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
John McCall0953e762009-09-24 19:53:00 +00001282 // If this type already has an address space specified, it cannot get
1283 // another one.
1284 assert(!Quals.hasAddressSpace() &&
1285 "Type cannot be in multiple addr spaces!");
1286 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001287
John McCall0953e762009-09-24 19:53:00 +00001288 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001289}
1290
Chris Lattnerb7d25532009-02-18 22:53:11 +00001291QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001292 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001293 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001294 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001295 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001297 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001298 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001299 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001300 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1301 return getPointerType(ResultType);
1302 }
1303 }
Mike Stump1eb44332009-09-09 15:08:12 +00001304
John McCall0953e762009-09-24 19:53:00 +00001305 // If we are composing extended qualifiers together, merge together
1306 // into one ExtQuals node.
1307 QualifierCollector Quals;
1308 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001309
John McCall0953e762009-09-24 19:53:00 +00001310 // If this type already has an ObjCGC specified, it cannot get
1311 // another one.
1312 assert(!Quals.hasObjCGCAttr() &&
1313 "Type cannot have multiple ObjCGCs!");
1314 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
John McCall0953e762009-09-24 19:53:00 +00001316 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001317}
Chris Lattnera7674d82007-07-13 22:13:22 +00001318
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001319static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1320 bool AddNoReturn,
1321 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001322 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001323 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1324 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001325 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1326 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001327 if (ResultType == Pointee)
1328 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001329
1330 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001331 } else if (const BlockPointerType *BlockPointer
1332 = T->getAs<BlockPointerType>()) {
1333 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001334 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1335 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001336 if (ResultType == Pointee)
1337 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001338
1339 ResultType = Context.getBlockPointerType(ResultType);
1340 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1341 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001342 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001343
Douglas Gregor43c79c22009-12-09 00:47:37 +00001344 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001345 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1346 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001347 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001348 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001349 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001350 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1351 FPT->getNumArgs(), FPT->isVariadic(),
1352 FPT->getTypeQuals(),
1353 FPT->hasExceptionSpec(),
1354 FPT->hasAnyExceptionSpec(),
1355 FPT->getNumExceptions(),
1356 FPT->exception_begin(),
1357 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001358 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001359 } else
1360 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001361
1362 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1363}
1364
1365QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1366 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1367}
1368
1369QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1370 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001371}
1372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373/// getComplexType - Return the uniqued reference to the type for a complex
1374/// number with the specified element type.
1375QualType ASTContext::getComplexType(QualType T) {
1376 // Unique pointers, to guarantee there is only one pointer of a particular
1377 // structure.
1378 llvm::FoldingSetNodeID ID;
1379 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 void *InsertPos = 0;
1382 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1383 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 // If the pointee type isn't canonical, this won't be a canonical type either,
1386 // so fill in the canonical type field.
1387 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001388 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001389 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 // Get the new insert position for the node we care about.
1392 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001393 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 }
John McCall6b304a02009-09-24 23:30:46 +00001395 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 Types.push_back(New);
1397 ComplexTypes.InsertNode(New, InsertPos);
1398 return QualType(New, 0);
1399}
1400
Reid Spencer5f016e22007-07-11 17:01:13 +00001401/// getPointerType - Return the uniqued reference to the type for a pointer to
1402/// the specified type.
1403QualType ASTContext::getPointerType(QualType T) {
1404 // Unique pointers, to guarantee there is only one pointer of a particular
1405 // structure.
1406 llvm::FoldingSetNodeID ID;
1407 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 void *InsertPos = 0;
1410 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1411 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 // If the pointee type isn't canonical, this won't be a canonical type either,
1414 // so fill in the canonical type field.
1415 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001416 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001417 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 // Get the new insert position for the node we care about.
1420 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001421 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 }
John McCall6b304a02009-09-24 23:30:46 +00001423 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 Types.push_back(New);
1425 PointerTypes.InsertNode(New, InsertPos);
1426 return QualType(New, 0);
1427}
1428
Mike Stump1eb44332009-09-09 15:08:12 +00001429/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001430/// a pointer to the specified block.
1431QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001432 assert(T->isFunctionType() && "block of function types only");
1433 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001434 // structure.
1435 llvm::FoldingSetNodeID ID;
1436 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Steve Naroff5618bd42008-08-27 16:04:49 +00001438 void *InsertPos = 0;
1439 if (BlockPointerType *PT =
1440 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1441 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
1443 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001444 // type either so fill in the canonical type field.
1445 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001446 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001447 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Steve Naroff5618bd42008-08-27 16:04:49 +00001449 // Get the new insert position for the node we care about.
1450 BlockPointerType *NewIP =
1451 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001452 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001453 }
John McCall6b304a02009-09-24 23:30:46 +00001454 BlockPointerType *New
1455 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001456 Types.push_back(New);
1457 BlockPointerTypes.InsertNode(New, InsertPos);
1458 return QualType(New, 0);
1459}
1460
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001461/// getLValueReferenceType - Return the uniqued reference to the type for an
1462/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001463QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // Unique pointers, to guarantee there is only one pointer of a particular
1465 // structure.
1466 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001467 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001468
1469 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001470 if (LValueReferenceType *RT =
1471 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001473
John McCall54e14c42009-10-22 22:37:11 +00001474 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // If the referencee type isn't canonical, this won't be a canonical type
1477 // either, so fill in the canonical type field.
1478 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001479 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1480 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1481 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001482
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001484 LValueReferenceType *NewIP =
1485 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001486 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 }
1488
John McCall6b304a02009-09-24 23:30:46 +00001489 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001490 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1491 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001493 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001494
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001495 return QualType(New, 0);
1496}
1497
1498/// getRValueReferenceType - Return the uniqued reference to the type for an
1499/// rvalue reference to the specified type.
1500QualType ASTContext::getRValueReferenceType(QualType T) {
1501 // Unique pointers, to guarantee there is only one pointer of a particular
1502 // structure.
1503 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001504 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001505
1506 void *InsertPos = 0;
1507 if (RValueReferenceType *RT =
1508 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1509 return QualType(RT, 0);
1510
John McCall54e14c42009-10-22 22:37:11 +00001511 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1512
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001513 // If the referencee type isn't canonical, this won't be a canonical type
1514 // either, so fill in the canonical type field.
1515 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001516 if (InnerRef || !T.isCanonical()) {
1517 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1518 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001519
1520 // Get the new insert position for the node we care about.
1521 RValueReferenceType *NewIP =
1522 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1523 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1524 }
1525
John McCall6b304a02009-09-24 23:30:46 +00001526 RValueReferenceType *New
1527 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001528 Types.push_back(New);
1529 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 return QualType(New, 0);
1531}
1532
Sebastian Redlf30208a2009-01-24 21:16:55 +00001533/// getMemberPointerType - Return the uniqued reference to the type for a
1534/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001535QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001536 // Unique pointers, to guarantee there is only one pointer of a particular
1537 // structure.
1538 llvm::FoldingSetNodeID ID;
1539 MemberPointerType::Profile(ID, T, Cls);
1540
1541 void *InsertPos = 0;
1542 if (MemberPointerType *PT =
1543 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1544 return QualType(PT, 0);
1545
1546 // If the pointee or class type isn't canonical, this won't be a canonical
1547 // type either, so fill in the canonical type field.
1548 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001549 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001550 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1551
1552 // Get the new insert position for the node we care about.
1553 MemberPointerType *NewIP =
1554 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1555 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1556 }
John McCall6b304a02009-09-24 23:30:46 +00001557 MemberPointerType *New
1558 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001559 Types.push_back(New);
1560 MemberPointerTypes.InsertNode(New, InsertPos);
1561 return QualType(New, 0);
1562}
1563
Mike Stump1eb44332009-09-09 15:08:12 +00001564/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001565/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001566QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001567 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001568 ArrayType::ArraySizeModifier ASM,
1569 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001570 assert((EltTy->isDependentType() ||
1571 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001572 "Constant array of VLAs is illegal!");
1573
Chris Lattner38aeec72009-05-13 04:12:56 +00001574 // Convert the array size into a canonical width matching the pointer size for
1575 // the target.
1576 llvm::APInt ArySize(ArySizeIn);
1577 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001580 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001583 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001584 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // If the element type isn't canonical, this won't be a canonical type either,
1588 // so fill in the canonical type field.
1589 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001590 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001591 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001592 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001594 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001595 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001596 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 }
Mike Stump1eb44332009-09-09 15:08:12 +00001598
John McCall6b304a02009-09-24 23:30:46 +00001599 ConstantArrayType *New = new(*this,TypeAlignment)
1600 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001601 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 Types.push_back(New);
1603 return QualType(New, 0);
1604}
1605
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001606/// getVariableArrayType - Returns a non-unique reference to the type for a
1607/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001608QualType ASTContext::getVariableArrayType(QualType EltTy,
1609 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001610 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001611 unsigned EltTypeQuals,
1612 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001613 // Since we don't unique expressions, it isn't possible to unique VLA's
1614 // that have an expression provided for their size.
1615
John McCall6b304a02009-09-24 23:30:46 +00001616 VariableArrayType *New = new(*this, TypeAlignment)
1617 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001618
1619 VariableArrayTypes.push_back(New);
1620 Types.push_back(New);
1621 return QualType(New, 0);
1622}
1623
Douglas Gregor898574e2008-12-05 23:32:09 +00001624/// getDependentSizedArrayType - Returns a non-unique reference to
1625/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001626/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001627QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1628 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001629 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001630 unsigned EltTypeQuals,
1631 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001632 assert((!NumElts || NumElts->isTypeDependent() ||
1633 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001634 "Size must be type- or value-dependent!");
1635
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001636 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001637 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001638 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001639
1640 if (NumElts) {
1641 // Dependently-sized array types that do not have a specified
1642 // number of elements will have their sizes deduced from an
1643 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001644 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1645 EltTypeQuals, NumElts);
1646
1647 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1648 }
1649
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001650 DependentSizedArrayType *New;
1651 if (Canon) {
1652 // We already have a canonical version of this array type; use it as
1653 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001654 New = new (*this, TypeAlignment)
1655 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1656 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001657 } else {
1658 QualType CanonEltTy = getCanonicalType(EltTy);
1659 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001660 New = new (*this, TypeAlignment)
1661 DependentSizedArrayType(*this, EltTy, QualType(),
1662 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001663
Douglas Gregor789b1f62010-02-04 18:10:26 +00001664 if (NumElts) {
1665 DependentSizedArrayType *CanonCheck
1666 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1667 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1668 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001669 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001670 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001671 } else {
1672 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1673 ASM, EltTypeQuals,
1674 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001675 New = new (*this, TypeAlignment)
1676 DependentSizedArrayType(*this, EltTy, Canon,
1677 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001678 }
1679 }
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Douglas Gregor898574e2008-12-05 23:32:09 +00001681 Types.push_back(New);
1682 return QualType(New, 0);
1683}
1684
Eli Friedmanc5773c42008-02-15 18:16:39 +00001685QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1686 ArrayType::ArraySizeModifier ASM,
1687 unsigned EltTypeQuals) {
1688 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001689 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001690
1691 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001692 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001693 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1694 return QualType(ATP, 0);
1695
1696 // If the element type isn't canonical, this won't be a canonical type
1697 // either, so fill in the canonical type field.
1698 QualType Canonical;
1699
John McCall467b27b2009-10-22 20:10:53 +00001700 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001701 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001702 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001703
1704 // Get the new insert position for the node we care about.
1705 IncompleteArrayType *NewIP =
1706 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001707 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001708 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001709
John McCall6b304a02009-09-24 23:30:46 +00001710 IncompleteArrayType *New = new (*this, TypeAlignment)
1711 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001712
1713 IncompleteArrayTypes.InsertNode(New, InsertPos);
1714 Types.push_back(New);
1715 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001716}
1717
Steve Naroff73322922007-07-18 18:00:27 +00001718/// getVectorType - Return the unique reference to a vector type of
1719/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001720QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1721 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Chris Lattnerf52ab252008-04-06 22:59:24 +00001724 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001725 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // Check if we've already instantiated a vector of this type.
1728 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001729 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1730 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 void *InsertPos = 0;
1732 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1733 return QualType(VTP, 0);
1734
1735 // If the element type isn't canonical, this won't be a canonical type either,
1736 // so fill in the canonical type field.
1737 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001738 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1739 Canonical = getVectorType(getCanonicalType(vecType),
1740 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 // Get the new insert position for the node we care about.
1743 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001744 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 }
John McCall6b304a02009-09-24 23:30:46 +00001746 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001747 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 VectorTypes.InsertNode(New, InsertPos);
1749 Types.push_back(New);
1750 return QualType(New, 0);
1751}
1752
Nate Begeman213541a2008-04-18 23:10:10 +00001753/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001754/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001755QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001756 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Chris Lattnerf52ab252008-04-06 22:59:24 +00001758 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001759 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Steve Naroff73322922007-07-18 18:00:27 +00001761 // Check if we've already instantiated a vector of this type.
1762 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001763 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001764 void *InsertPos = 0;
1765 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1766 return QualType(VTP, 0);
1767
1768 // If the element type isn't canonical, this won't be a canonical type either,
1769 // so fill in the canonical type field.
1770 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001771 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001772 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Steve Naroff73322922007-07-18 18:00:27 +00001774 // Get the new insert position for the node we care about.
1775 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001776 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001777 }
John McCall6b304a02009-09-24 23:30:46 +00001778 ExtVectorType *New = new (*this, TypeAlignment)
1779 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001780 VectorTypes.InsertNode(New, InsertPos);
1781 Types.push_back(New);
1782 return QualType(New, 0);
1783}
1784
Mike Stump1eb44332009-09-09 15:08:12 +00001785QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001786 Expr *SizeExpr,
1787 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001788 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001789 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001790 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001792 void *InsertPos = 0;
1793 DependentSizedExtVectorType *Canon
1794 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1795 DependentSizedExtVectorType *New;
1796 if (Canon) {
1797 // We already have a canonical version of this array type; use it as
1798 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001799 New = new (*this, TypeAlignment)
1800 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1801 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001802 } else {
1803 QualType CanonVecTy = getCanonicalType(vecType);
1804 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001805 New = new (*this, TypeAlignment)
1806 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1807 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001808
1809 DependentSizedExtVectorType *CanonCheck
1810 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1811 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1812 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001813 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1814 } else {
1815 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1816 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001817 New = new (*this, TypeAlignment)
1818 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001819 }
1820 }
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001822 Types.push_back(New);
1823 return QualType(New, 0);
1824}
1825
Douglas Gregor72564e72009-02-26 23:50:07 +00001826/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001827///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001828QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1829 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 // Unique functions, to guarantee there is only one function of a particular
1831 // structure.
1832 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001833 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001836 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001837 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001841 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001842 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001843 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001844 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001847 FunctionNoProtoType *NewIP =
1848 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001849 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 }
Mike Stump1eb44332009-09-09 15:08:12 +00001851
John McCall6b304a02009-09-24 23:30:46 +00001852 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001853 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001855 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 return QualType(New, 0);
1857}
1858
1859/// getFunctionType - Return a normal function type with a typed argument
1860/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001861QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001862 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001863 unsigned TypeQuals, bool hasExceptionSpec,
1864 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001865 const QualType *ExArray, bool NoReturn,
1866 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 // Unique functions, to guarantee there is only one function of a particular
1868 // structure.
1869 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001870 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001871 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001872 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001873
1874 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001875 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001876 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001878
1879 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001880 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001882 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 isCanonical = false;
1884
1885 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001886 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001888 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 llvm::SmallVector<QualType, 16> CanonicalArgs;
1890 CanonicalArgs.reserve(NumArgs);
1891 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001892 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001893
Chris Lattnerf52ab252008-04-06 22:59:24 +00001894 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001895 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001896 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001897 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001898 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001899
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001901 FunctionProtoType *NewIP =
1902 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001903 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001905
Douglas Gregor72564e72009-02-26 23:50:07 +00001906 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001907 // for two variable size arrays (for parameter and exception types) at the
1908 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001909 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001910 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1911 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001912 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001913 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001914 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001915 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001917 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 return QualType(FTP, 0);
1919}
1920
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001921/// getTypeDeclType - Return the unique reference to the type for the
1922/// specified type declaration.
John McCall19c85762010-02-16 03:57:14 +00001923QualType ASTContext::getTypeDeclType(const TypeDecl *Decl,
1924 const TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001925 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001926 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
John McCall19c85762010-02-16 03:57:14 +00001928 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001929 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001930 else if (isa<TemplateTypeParmDecl>(Decl)) {
1931 assert(false && "Template type parameter types are always available.");
John McCall19c85762010-02-16 03:57:14 +00001932 } else if (const ObjCInterfaceDecl *ObjCInterface
Mike Stump9fdbab32009-07-31 02:02:20 +00001933 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001934 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001935
John McCall19c85762010-02-16 03:57:14 +00001936 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001937 if (PrevDecl)
1938 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001939 else
John McCall6b304a02009-09-24 23:30:46 +00001940 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001941 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001942 if (PrevDecl)
1943 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001944 else
John McCall6b304a02009-09-24 23:30:46 +00001945 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001946 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001947 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1948 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001949 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001950 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001951
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001952 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001953 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001954}
1955
Reid Spencer5f016e22007-07-11 17:01:13 +00001956/// getTypedefType - Return the unique reference to the type for the
1957/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001958QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Chris Lattnerf52ab252008-04-06 22:59:24 +00001961 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001962 Decl->TypeForDecl = new(*this, TypeAlignment)
1963 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 Types.push_back(Decl->TypeForDecl);
1965 return QualType(Decl->TypeForDecl, 0);
1966}
1967
John McCall49a832b2009-10-18 09:09:24 +00001968/// \brief Retrieve a substitution-result type.
1969QualType
1970ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1971 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001972 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001973 && "replacement types must always be canonical");
1974
1975 llvm::FoldingSetNodeID ID;
1976 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1977 void *InsertPos = 0;
1978 SubstTemplateTypeParmType *SubstParm
1979 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1980
1981 if (!SubstParm) {
1982 SubstParm = new (*this, TypeAlignment)
1983 SubstTemplateTypeParmType(Parm, Replacement);
1984 Types.push_back(SubstParm);
1985 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1986 }
1987
1988 return QualType(SubstParm, 0);
1989}
1990
Douglas Gregorfab9d672009-02-05 23:33:38 +00001991/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001992/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001993/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001994QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001995 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001996 IdentifierInfo *Name) {
1997 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001998 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001999 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002000 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002001 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2002
2003 if (TypeParm)
2004 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002006 if (Name) {
2007 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00002008 TypeParm = new (*this, TypeAlignment)
2009 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002010
2011 TemplateTypeParmType *TypeCheck
2012 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2013 assert(!TypeCheck && "Template type parameter canonical type broken");
2014 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002015 } else
John McCall6b304a02009-09-24 23:30:46 +00002016 TypeParm = new (*this, TypeAlignment)
2017 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002018
2019 Types.push_back(TypeParm);
2020 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2021
2022 return QualType(TypeParm, 0);
2023}
2024
Mike Stump1eb44332009-09-09 15:08:12 +00002025QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002026ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002027 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00002028 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00002029 unsigned NumArgs = Args.size();
2030
John McCall833ca992009-10-29 08:12:44 +00002031 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2032 ArgVec.reserve(NumArgs);
2033 for (unsigned i = 0; i != NumArgs; ++i)
2034 ArgVec.push_back(Args[i].getArgument());
2035
2036 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2037}
2038
2039QualType
2040ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002041 const TemplateArgument *Args,
2042 unsigned NumArgs,
2043 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002044 if (!Canon.isNull())
2045 Canon = getCanonicalType(Canon);
2046 else {
2047 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00002048 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2049 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2050 CanonArgs.reserve(NumArgs);
2051 for (unsigned I = 0; I != NumArgs; ++I)
2052 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2053
2054 // Determine whether this canonical template specialization type already
2055 // exists.
2056 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002057 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00002058 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002059
2060 void *InsertPos = 0;
2061 TemplateSpecializationType *Spec
2062 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregor1275ae02009-07-28 23:00:59 +00002064 if (!Spec) {
2065 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00002066 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00002067 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002068 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002069 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00002070 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00002071 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002072 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002073 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Douglas Gregorb88e8882009-07-30 17:40:51 +00002076 if (Canon.isNull())
2077 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002078 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00002079 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00002080 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002081
Douglas Gregor1275ae02009-07-28 23:00:59 +00002082 // Allocate the (non-canonical) template specialization type, but don't
2083 // try to unique it: these types typically have location information that
2084 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002085 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002086 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002087 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002088 TemplateSpecializationType *Spec
2089 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002090 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Douglas Gregor55f6b142009-02-09 18:46:07 +00002092 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002093 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002094}
2095
Mike Stump1eb44332009-09-09 15:08:12 +00002096QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00002097ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00002098 QualType NamedType) {
2099 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00002100 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002101
2102 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002103 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00002104 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 if (T)
2106 return QualType(T, 0);
2107
Douglas Gregor789b1f62010-02-04 18:10:26 +00002108 QualType Canon = NamedType;
2109 if (!Canon.isCanonical()) {
2110 Canon = getCanonicalType(NamedType);
2111 QualifiedNameType *CheckT
2112 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2113 assert(!CheckT && "Qualified name canonical type broken");
2114 (void)CheckT;
2115 }
2116
2117 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002118 Types.push_back(T);
2119 QualifiedNameTypes.InsertNode(T, InsertPos);
2120 return QualType(T, 0);
2121}
2122
Mike Stump1eb44332009-09-09 15:08:12 +00002123QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002124 const IdentifierInfo *Name,
2125 QualType Canon) {
2126 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2127
2128 if (Canon.isNull()) {
2129 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2130 if (CanonNNS != NNS)
2131 Canon = getTypenameType(CanonNNS, Name);
2132 }
2133
2134 llvm::FoldingSetNodeID ID;
2135 TypenameType::Profile(ID, NNS, Name);
2136
2137 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002138 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002139 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2140 if (T)
2141 return QualType(T, 0);
2142
2143 T = new (*this) TypenameType(NNS, Name, Canon);
2144 Types.push_back(T);
2145 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002146 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002147}
2148
Mike Stump1eb44332009-09-09 15:08:12 +00002149QualType
2150ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002151 const TemplateSpecializationType *TemplateId,
2152 QualType Canon) {
2153 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2154
Douglas Gregor789b1f62010-02-04 18:10:26 +00002155 llvm::FoldingSetNodeID ID;
2156 TypenameType::Profile(ID, NNS, TemplateId);
2157
2158 void *InsertPos = 0;
2159 TypenameType *T
2160 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2161 if (T)
2162 return QualType(T, 0);
2163
Douglas Gregor17343172009-04-01 00:28:59 +00002164 if (Canon.isNull()) {
2165 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2166 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2167 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2168 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002169 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002170 assert(CanonTemplateId &&
2171 "Canonical type must also be a template specialization type");
2172 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2173 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002174
2175 TypenameType *CheckT
2176 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2177 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002178 }
2179
Douglas Gregor17343172009-04-01 00:28:59 +00002180 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2181 Types.push_back(T);
2182 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002183 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002184}
2185
John McCall7da24312009-09-05 00:15:47 +00002186QualType
2187ASTContext::getElaboratedType(QualType UnderlyingType,
2188 ElaboratedType::TagKind Tag) {
2189 llvm::FoldingSetNodeID ID;
2190 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002191
John McCall7da24312009-09-05 00:15:47 +00002192 void *InsertPos = 0;
2193 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2194 if (T)
2195 return QualType(T, 0);
2196
Douglas Gregor789b1f62010-02-04 18:10:26 +00002197 QualType Canon = UnderlyingType;
2198 if (!Canon.isCanonical()) {
2199 Canon = getCanonicalType(Canon);
2200 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2201 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2202 }
John McCall7da24312009-09-05 00:15:47 +00002203
2204 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2205 Types.push_back(T);
2206 ElaboratedTypes.InsertNode(T, InsertPos);
2207 return QualType(T, 0);
2208}
2209
Chris Lattner88cb27a2008-04-07 04:56:42 +00002210/// CmpProtocolNames - Comparison predicate for sorting protocols
2211/// alphabetically.
2212static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2213 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002214 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002215}
2216
John McCall54e14c42009-10-22 22:37:11 +00002217static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2218 unsigned NumProtocols) {
2219 if (NumProtocols == 0) return true;
2220
2221 for (unsigned i = 1; i != NumProtocols; ++i)
2222 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2223 return false;
2224 return true;
2225}
2226
2227static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002228 unsigned &NumProtocols) {
2229 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Chris Lattner88cb27a2008-04-07 04:56:42 +00002231 // Sort protocols, keyed by name.
2232 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2233
2234 // Remove duplicates.
2235 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2236 NumProtocols = ProtocolsEnd-Protocols;
2237}
2238
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002239/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2240/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002241QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002242 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002243 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002244 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002245 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002246
2247 void *InsertPos = 0;
2248 if (ObjCObjectPointerType *QT =
2249 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2250 return QualType(QT, 0);
2251
John McCall54e14c42009-10-22 22:37:11 +00002252 // Sort the protocol list alphabetically to canonicalize it.
2253 QualType Canonical;
2254 if (!InterfaceT.isCanonical() ||
2255 !areSortedAndUniqued(Protocols, NumProtocols)) {
2256 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2257 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2258 unsigned UniqueCount = NumProtocols;
2259
2260 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2261 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2262
2263 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2264 &Sorted[0], UniqueCount);
2265 } else {
2266 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2267 Protocols, NumProtocols);
2268 }
2269
2270 // Regenerate InsertPos.
2271 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2272 }
2273
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002274 // No match.
2275 unsigned Size = sizeof(ObjCObjectPointerType)
2276 + NumProtocols * sizeof(ObjCProtocolDecl *);
2277 void *Mem = Allocate(Size, TypeAlignment);
2278 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2279 InterfaceT,
2280 Protocols,
2281 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002283 Types.push_back(QType);
2284 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2285 return QualType(QType, 0);
2286}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002287
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002288/// getObjCInterfaceType - Return the unique reference to the type for the
2289/// specified ObjC interface decl. The list of protocols is optional.
2290QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002291 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002292 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002293 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002295 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002296 if (ObjCInterfaceType *QT =
2297 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002298 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
John McCall54e14c42009-10-22 22:37:11 +00002300 // Sort the protocol list alphabetically to canonicalize it.
2301 QualType Canonical;
2302 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2303 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2304 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2305
2306 unsigned UniqueCount = NumProtocols;
2307 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2308
2309 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2310
2311 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2312 }
2313
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002314 unsigned Size = sizeof(ObjCInterfaceType)
2315 + NumProtocols * sizeof(ObjCProtocolDecl *);
2316 void *Mem = Allocate(Size, TypeAlignment);
2317 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2318 const_cast<ObjCInterfaceDecl*>(Decl),
2319 Protocols,
2320 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002321
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002322 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002323 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002324 return QualType(QType, 0);
2325}
2326
Douglas Gregor72564e72009-02-26 23:50:07 +00002327/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2328/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002329/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002330/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002331/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002332QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002333 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002334 if (tofExpr->isTypeDependent()) {
2335 llvm::FoldingSetNodeID ID;
2336 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Douglas Gregorb1975722009-07-30 23:18:24 +00002338 void *InsertPos = 0;
2339 DependentTypeOfExprType *Canon
2340 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2341 if (Canon) {
2342 // We already have a "canonical" version of an identical, dependent
2343 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002344 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002345 QualType((TypeOfExprType*)Canon, 0));
2346 }
2347 else {
2348 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002349 Canon
2350 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002351 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2352 toe = Canon;
2353 }
2354 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002355 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002356 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002357 }
Steve Naroff9752f252007-08-01 18:02:17 +00002358 Types.push_back(toe);
2359 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002360}
2361
Steve Naroff9752f252007-08-01 18:02:17 +00002362/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2363/// TypeOfType AST's. The only motivation to unique these nodes would be
2364/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002365/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002366/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002367QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002368 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002369 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002370 Types.push_back(tot);
2371 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002372}
2373
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002374/// getDecltypeForExpr - Given an expr, will return the decltype for that
2375/// expression, according to the rules in C++0x [dcl.type.simple]p4
2376static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002377 if (e->isTypeDependent())
2378 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002380 // If e is an id expression or a class member access, decltype(e) is defined
2381 // as the type of the entity named by e.
2382 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2383 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2384 return VD->getType();
2385 }
2386 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2387 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2388 return FD->getType();
2389 }
2390 // If e is a function call or an invocation of an overloaded operator,
2391 // (parentheses around e are ignored), decltype(e) is defined as the
2392 // return type of that function.
2393 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2394 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002396 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002397
2398 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002399 // defined as T&, otherwise decltype(e) is defined as T.
2400 if (e->isLvalue(Context) == Expr::LV_Valid)
2401 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002403 return T;
2404}
2405
Anders Carlsson395b4752009-06-24 19:06:50 +00002406/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2407/// DecltypeType AST's. The only motivation to unique these nodes would be
2408/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002409/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002410/// on canonical type's (which are always unique).
2411QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002412 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002413 if (e->isTypeDependent()) {
2414 llvm::FoldingSetNodeID ID;
2415 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002417 void *InsertPos = 0;
2418 DependentDecltypeType *Canon
2419 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2420 if (Canon) {
2421 // We already have a "canonical" version of an equivalent, dependent
2422 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002423 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002424 QualType((DecltypeType*)Canon, 0));
2425 }
2426 else {
2427 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002428 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002429 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2430 dt = Canon;
2431 }
2432 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002433 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002434 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002435 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002436 Types.push_back(dt);
2437 return QualType(dt, 0);
2438}
2439
Reid Spencer5f016e22007-07-11 17:01:13 +00002440/// getTagDeclType - Return the unique reference to the type for the
2441/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002442QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002443 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002444 // FIXME: What is the design on getTagDeclType when it requires casting
2445 // away const? mutable?
2446 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002447}
2448
Mike Stump1eb44332009-09-09 15:08:12 +00002449/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2450/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2451/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002452CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002453 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002454}
2455
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002456/// getSignedWCharType - Return the type of "signed wchar_t".
2457/// Used when in C++, as a GCC extension.
2458QualType ASTContext::getSignedWCharType() const {
2459 // FIXME: derive from "Target" ?
2460 return WCharTy;
2461}
2462
2463/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2464/// Used when in C++, as a GCC extension.
2465QualType ASTContext::getUnsignedWCharType() const {
2466 // FIXME: derive from "Target" ?
2467 return UnsignedIntTy;
2468}
2469
Chris Lattner8b9023b2007-07-13 03:05:23 +00002470/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2471/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2472QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002473 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002474}
2475
Chris Lattnere6327742008-04-02 05:18:44 +00002476//===----------------------------------------------------------------------===//
2477// Type Operators
2478//===----------------------------------------------------------------------===//
2479
John McCall54e14c42009-10-22 22:37:11 +00002480CanQualType ASTContext::getCanonicalParamType(QualType T) {
2481 // Push qualifiers into arrays, and then discard any remaining
2482 // qualifiers.
2483 T = getCanonicalType(T);
2484 const Type *Ty = T.getTypePtr();
2485
2486 QualType Result;
2487 if (isa<ArrayType>(Ty)) {
2488 Result = getArrayDecayedType(QualType(Ty,0));
2489 } else if (isa<FunctionType>(Ty)) {
2490 Result = getPointerType(QualType(Ty, 0));
2491 } else {
2492 Result = QualType(Ty, 0);
2493 }
2494
2495 return CanQualType::CreateUnsafe(Result);
2496}
2497
Chris Lattner77c96472008-04-06 22:41:35 +00002498/// getCanonicalType - Return the canonical (structural) type corresponding to
2499/// the specified potentially non-canonical type. The non-canonical version
2500/// of a type may have many "decorated" versions of types. Decorators can
2501/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2502/// to be free of any of these, allowing two canonical types to be compared
2503/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002504CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002505 QualifierCollector Quals;
2506 const Type *Ptr = Quals.strip(T);
2507 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002508
John McCall0953e762009-09-24 19:53:00 +00002509 // The canonical internal type will be the canonical type *except*
2510 // that we push type qualifiers down through array types.
2511
2512 // If there are no new qualifiers to push down, stop here.
2513 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002514 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002515
John McCall0953e762009-09-24 19:53:00 +00002516 // If the type qualifiers are on an array type, get the canonical
2517 // type of the array with the qualifiers applied to the element
2518 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002519 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2520 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002521 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002523 // Get the canonical version of the element with the extra qualifiers on it.
2524 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002525 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002526 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002528 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002529 return CanQualType::CreateUnsafe(
2530 getConstantArrayType(NewEltTy, CAT->getSize(),
2531 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002532 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002533 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002534 return CanQualType::CreateUnsafe(
2535 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002536 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregor898574e2008-12-05 23:32:09 +00002538 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002539 return CanQualType::CreateUnsafe(
2540 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002541 DSAT->getSizeExpr() ?
2542 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002543 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002544 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002545 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002546
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002547 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002548 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002549 VAT->getSizeExpr() ?
2550 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002551 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002552 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002553 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002554}
2555
Chandler Carruth28e318c2009-12-29 07:16:59 +00002556QualType ASTContext::getUnqualifiedArrayType(QualType T,
2557 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002558 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002559 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002560 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002561 }
2562
Chandler Carruth28e318c2009-12-29 07:16:59 +00002563 const ArrayType *AT = cast<ArrayType>(T);
2564 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002565 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002566 if (Elt == UnqualElt)
2567 return T;
2568
2569 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2570 return getConstantArrayType(UnqualElt, CAT->getSize(),
2571 CAT->getSizeModifier(), 0);
2572 }
2573
2574 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2575 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2576 }
2577
2578 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2579 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2580 DSAT->getSizeModifier(), 0,
2581 SourceRange());
2582}
2583
John McCall80ad16f2009-11-24 18:42:40 +00002584DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2585 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2586 return TD->getDeclName();
2587
2588 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2589 if (DTN->isIdentifier()) {
2590 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2591 } else {
2592 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2593 }
2594 }
2595
John McCall0bd6feb2009-12-02 08:04:21 +00002596 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2597 assert(Storage);
2598 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002599}
2600
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002601TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2602 // If this template name refers to a template, the canonical
2603 // template name merely stores the template itself.
2604 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002605 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002606
John McCall0bd6feb2009-12-02 08:04:21 +00002607 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002608
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002609 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2610 assert(DTN && "Non-dependent template names must refer to template decls.");
2611 return DTN->CanonicalTemplateName;
2612}
2613
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002614bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2615 X = getCanonicalTemplateName(X);
2616 Y = getCanonicalTemplateName(Y);
2617 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2618}
2619
Mike Stump1eb44332009-09-09 15:08:12 +00002620TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002621ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2622 switch (Arg.getKind()) {
2623 case TemplateArgument::Null:
2624 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Douglas Gregor1275ae02009-07-28 23:00:59 +00002626 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002627 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Douglas Gregor1275ae02009-07-28 23:00:59 +00002629 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002630 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Douglas Gregor788cd062009-11-11 01:00:40 +00002632 case TemplateArgument::Template:
2633 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2634
Douglas Gregor1275ae02009-07-28 23:00:59 +00002635 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002636 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002637 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Douglas Gregor1275ae02009-07-28 23:00:59 +00002639 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002640 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Douglas Gregor1275ae02009-07-28 23:00:59 +00002642 case TemplateArgument::Pack: {
2643 // FIXME: Allocate in ASTContext
2644 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2645 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002646 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002647 AEnd = Arg.pack_end();
2648 A != AEnd; (void)++A, ++Idx)
2649 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Douglas Gregor1275ae02009-07-28 23:00:59 +00002651 TemplateArgument Result;
2652 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2653 return Result;
2654 }
2655 }
2656
2657 // Silence GCC warning
2658 assert(false && "Unhandled template argument kind");
2659 return TemplateArgument();
2660}
2661
Douglas Gregord57959a2009-03-27 23:10:48 +00002662NestedNameSpecifier *
2663ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002664 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002665 return 0;
2666
2667 switch (NNS->getKind()) {
2668 case NestedNameSpecifier::Identifier:
2669 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002670 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002671 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2672 NNS->getAsIdentifier());
2673
2674 case NestedNameSpecifier::Namespace:
2675 // A namespace is canonical; build a nested-name-specifier with
2676 // this namespace and no prefix.
2677 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2678
2679 case NestedNameSpecifier::TypeSpec:
2680 case NestedNameSpecifier::TypeSpecWithTemplate: {
2681 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002682 return NestedNameSpecifier::Create(*this, 0,
2683 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002684 T.getTypePtr());
2685 }
2686
2687 case NestedNameSpecifier::Global:
2688 // The global specifier is canonical and unique.
2689 return NNS;
2690 }
2691
2692 // Required to silence a GCC warning
2693 return 0;
2694}
2695
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002696
2697const ArrayType *ASTContext::getAsArrayType(QualType T) {
2698 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002699 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002700 // Handle the common positive case fast.
2701 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2702 return AT;
2703 }
Mike Stump1eb44332009-09-09 15:08:12 +00002704
John McCall0953e762009-09-24 19:53:00 +00002705 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002706 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002707 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002708 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002709
John McCall0953e762009-09-24 19:53:00 +00002710 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002711 // implements C99 6.7.3p8: "If the specification of an array type includes
2712 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002714 // If we get here, we either have type qualifiers on the type, or we have
2715 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002716 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002717
John McCall0953e762009-09-24 19:53:00 +00002718 QualifierCollector Qs;
2719 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002721 // If we have a simple case, just return now.
2722 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002723 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002724 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002726 // Otherwise, we have an array and we have qualifiers on it. Push the
2727 // qualifiers into the array element type and return a new array type.
2728 // Get the canonical version of the element with the extra qualifiers on it.
2729 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002730 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002732 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2733 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2734 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002735 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002736 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2737 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2738 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002739 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002740
Mike Stump1eb44332009-09-09 15:08:12 +00002741 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002742 = dyn_cast<DependentSizedArrayType>(ATy))
2743 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002744 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002745 DSAT->getSizeExpr() ?
2746 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002747 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002748 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002749 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002751 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002752 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002753 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002754 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002755 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002756 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002757 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002758}
2759
2760
Chris Lattnere6327742008-04-02 05:18:44 +00002761/// getArrayDecayedType - Return the properly qualified result of decaying the
2762/// specified array type to a pointer. This operation is non-trivial when
2763/// handling typedefs etc. The canonical type of "T" must be an array type,
2764/// this returns a pointer to a properly qualified element of the array.
2765///
2766/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2767QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002768 // Get the element type with 'getAsArrayType' so that we don't lose any
2769 // typedefs in the element type of the array. This also handles propagation
2770 // of type qualifiers from the array type into the element type if present
2771 // (C99 6.7.3p8).
2772 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2773 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002775 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002776
2777 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002778 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002779}
2780
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002781QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002782 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002783 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002784 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002785 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2786 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002787 } else {
John McCall0953e762009-09-24 19:53:00 +00002788 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002789 }
2790 }
2791}
2792
Anders Carlssonfbbce492009-09-25 01:23:32 +00002793QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2794 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Anders Carlssonfbbce492009-09-25 01:23:32 +00002796 if (const ArrayType *AT = getAsArrayType(ElemTy))
2797 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Anders Carlsson6183a992008-12-21 03:44:36 +00002799 return ElemTy;
2800}
2801
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002802/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002803uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002804ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2805 uint64_t ElementCount = 1;
2806 do {
2807 ElementCount *= CA->getSize().getZExtValue();
2808 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2809 } while (CA);
2810 return ElementCount;
2811}
2812
Reid Spencer5f016e22007-07-11 17:01:13 +00002813/// getFloatingRank - Return a relative rank for floating point types.
2814/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002815static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002816 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002818
John McCall183700f2009-09-21 23:43:11 +00002819 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2820 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002821 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 case BuiltinType::Float: return FloatRank;
2823 case BuiltinType::Double: return DoubleRank;
2824 case BuiltinType::LongDouble: return LongDoubleRank;
2825 }
2826}
2827
Mike Stump1eb44332009-09-09 15:08:12 +00002828/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2829/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002830/// 'typeDomain' is a real floating point or complex type.
2831/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002832QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2833 QualType Domain) const {
2834 FloatingRank EltRank = getFloatingRank(Size);
2835 if (Domain->isComplexType()) {
2836 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002837 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002838 case FloatRank: return FloatComplexTy;
2839 case DoubleRank: return DoubleComplexTy;
2840 case LongDoubleRank: return LongDoubleComplexTy;
2841 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 }
Chris Lattner1361b112008-04-06 23:58:54 +00002843
2844 assert(Domain->isRealFloatingType() && "Unknown domain!");
2845 switch (EltRank) {
2846 default: assert(0 && "getFloatingRank(): illegal value for rank");
2847 case FloatRank: return FloatTy;
2848 case DoubleRank: return DoubleTy;
2849 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002850 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002851}
2852
Chris Lattner7cfeb082008-04-06 23:55:33 +00002853/// getFloatingTypeOrder - Compare the rank of the two specified floating
2854/// point types, ignoring the domain of the type (i.e. 'double' ==
2855/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002856/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002857int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2858 FloatingRank LHSR = getFloatingRank(LHS);
2859 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Chris Lattnera75cea32008-04-06 23:38:49 +00002861 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002862 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002863 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002864 return 1;
2865 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866}
2867
Chris Lattnerf52ab252008-04-06 22:59:24 +00002868/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2869/// routine will assert if passed a built-in type that isn't an integer or enum,
2870/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002871unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002872 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002873 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002874 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002875
Eli Friedmana3426752009-07-05 23:44:27 +00002876 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2877 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2878
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002879 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2880 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2881
2882 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2883 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2884
Chris Lattnerf52ab252008-04-06 22:59:24 +00002885 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002886 default: assert(0 && "getIntegerRank(): not a built-in integer");
2887 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002888 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002889 case BuiltinType::Char_S:
2890 case BuiltinType::Char_U:
2891 case BuiltinType::SChar:
2892 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002893 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002894 case BuiltinType::Short:
2895 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002896 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002897 case BuiltinType::Int:
2898 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002899 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002900 case BuiltinType::Long:
2901 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002902 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002903 case BuiltinType::LongLong:
2904 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002905 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002906 case BuiltinType::Int128:
2907 case BuiltinType::UInt128:
2908 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002909 }
2910}
2911
Eli Friedman04e83572009-08-20 04:21:42 +00002912/// \brief Whether this is a promotable bitfield reference according
2913/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2914///
2915/// \returns the type this bit-field will promote to, or NULL if no
2916/// promotion occurs.
2917QualType ASTContext::isPromotableBitField(Expr *E) {
2918 FieldDecl *Field = E->getBitField();
2919 if (!Field)
2920 return QualType();
2921
2922 QualType FT = Field->getType();
2923
2924 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2925 uint64_t BitWidth = BitWidthAP.getZExtValue();
2926 uint64_t IntSize = getTypeSize(IntTy);
2927 // GCC extension compatibility: if the bit-field size is less than or equal
2928 // to the size of int, it gets promoted no matter what its type is.
2929 // For instance, unsigned long bf : 4 gets promoted to signed int.
2930 if (BitWidth < IntSize)
2931 return IntTy;
2932
2933 if (BitWidth == IntSize)
2934 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2935
2936 // Types bigger than int are not subject to promotions, and therefore act
2937 // like the base type.
2938 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2939 // is ridiculous.
2940 return QualType();
2941}
2942
Eli Friedmana95d7572009-08-19 07:44:53 +00002943/// getPromotedIntegerType - Returns the type that Promotable will
2944/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2945/// integer type.
2946QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2947 assert(!Promotable.isNull());
2948 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002949 if (const EnumType *ET = Promotable->getAs<EnumType>())
2950 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002951 if (Promotable->isSignedIntegerType())
2952 return IntTy;
2953 uint64_t PromotableSize = getTypeSize(Promotable);
2954 uint64_t IntSize = getTypeSize(IntTy);
2955 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2956 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2957}
2958
Mike Stump1eb44332009-09-09 15:08:12 +00002959/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002960/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002961/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002962int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002963 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2964 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002965 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Chris Lattnerf52ab252008-04-06 22:59:24 +00002967 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2968 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Chris Lattner7cfeb082008-04-06 23:55:33 +00002970 unsigned LHSRank = getIntegerRank(LHSC);
2971 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Chris Lattner7cfeb082008-04-06 23:55:33 +00002973 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2974 if (LHSRank == RHSRank) return 0;
2975 return LHSRank > RHSRank ? 1 : -1;
2976 }
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Chris Lattner7cfeb082008-04-06 23:55:33 +00002978 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2979 if (LHSUnsigned) {
2980 // If the unsigned [LHS] type is larger, return it.
2981 if (LHSRank >= RHSRank)
2982 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002983
Chris Lattner7cfeb082008-04-06 23:55:33 +00002984 // If the signed type can represent all values of the unsigned type, it
2985 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002986 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002987 return -1;
2988 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002989
Chris Lattner7cfeb082008-04-06 23:55:33 +00002990 // If the unsigned [RHS] type is larger, return it.
2991 if (RHSRank >= LHSRank)
2992 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Chris Lattner7cfeb082008-04-06 23:55:33 +00002994 // If the signed type can represent all values of the unsigned type, it
2995 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002996 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002997 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002998}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002999
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003000static RecordDecl *
3001CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3002 SourceLocation L, IdentifierInfo *Id) {
3003 if (Ctx.getLangOptions().CPlusPlus)
3004 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3005 else
3006 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3007}
3008
Mike Stump1eb44332009-09-09 15:08:12 +00003009// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003010QualType ASTContext::getCFConstantStringType() {
3011 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003012 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003013 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3014 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003015 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003016
Anders Carlssonf06273f2007-11-19 00:25:30 +00003017 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Anders Carlsson71993dd2007-08-17 05:31:46 +00003019 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003020 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003021 // int flags;
3022 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003023 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003024 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003025 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003026 FieldTypes[3] = LongTy;
3027
Anders Carlsson71993dd2007-08-17 05:31:46 +00003028 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003029 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003030 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003031 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003032 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003033 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003034 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003035 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003036 }
3037
Douglas Gregor838db382010-02-11 01:19:42 +00003038 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003039 }
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Anders Carlsson71993dd2007-08-17 05:31:46 +00003041 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003042}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003043
Douglas Gregor319ac892009-04-23 22:29:11 +00003044void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003045 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003046 assert(Rec && "Invalid CFConstantStringType");
3047 CFConstantStringTypeDecl = Rec->getDecl();
3048}
3049
Mike Stump1eb44332009-09-09 15:08:12 +00003050QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003051 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003052 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003053 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3054 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003055 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003057 QualType FieldTypes[] = {
3058 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003059 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003060 getPointerType(UnsignedLongTy),
3061 getConstantArrayType(UnsignedLongTy,
3062 llvm::APInt(32, 5), ArrayType::Normal, 0)
3063 };
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Douglas Gregor44b43212008-12-11 16:49:14 +00003065 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003066 FieldDecl *Field = FieldDecl::Create(*this,
3067 ObjCFastEnumerationStateTypeDecl,
3068 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003069 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003070 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003071 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003072 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003073 }
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Douglas Gregor838db382010-02-11 01:19:42 +00003075 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003078 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3079}
3080
Mike Stumpadaaad32009-10-20 02:12:22 +00003081QualType ASTContext::getBlockDescriptorType() {
3082 if (BlockDescriptorType)
3083 return getTagDeclType(BlockDescriptorType);
3084
3085 RecordDecl *T;
3086 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003087 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3088 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003089 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003090
3091 QualType FieldTypes[] = {
3092 UnsignedLongTy,
3093 UnsignedLongTy,
3094 };
3095
3096 const char *FieldNames[] = {
3097 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003098 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003099 };
3100
3101 for (size_t i = 0; i < 2; ++i) {
3102 FieldDecl *Field = FieldDecl::Create(*this,
3103 T,
3104 SourceLocation(),
3105 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003106 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003107 /*BitWidth=*/0,
3108 /*Mutable=*/false);
3109 T->addDecl(Field);
3110 }
3111
Douglas Gregor838db382010-02-11 01:19:42 +00003112 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003113
3114 BlockDescriptorType = T;
3115
3116 return getTagDeclType(BlockDescriptorType);
3117}
3118
3119void ASTContext::setBlockDescriptorType(QualType T) {
3120 const RecordType *Rec = T->getAs<RecordType>();
3121 assert(Rec && "Invalid BlockDescriptorType");
3122 BlockDescriptorType = Rec->getDecl();
3123}
3124
Mike Stump083c25e2009-10-22 00:49:09 +00003125QualType ASTContext::getBlockDescriptorExtendedType() {
3126 if (BlockDescriptorExtendedType)
3127 return getTagDeclType(BlockDescriptorExtendedType);
3128
3129 RecordDecl *T;
3130 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003131 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3132 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003133 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003134
3135 QualType FieldTypes[] = {
3136 UnsignedLongTy,
3137 UnsignedLongTy,
3138 getPointerType(VoidPtrTy),
3139 getPointerType(VoidPtrTy)
3140 };
3141
3142 const char *FieldNames[] = {
3143 "reserved",
3144 "Size",
3145 "CopyFuncPtr",
3146 "DestroyFuncPtr"
3147 };
3148
3149 for (size_t i = 0; i < 4; ++i) {
3150 FieldDecl *Field = FieldDecl::Create(*this,
3151 T,
3152 SourceLocation(),
3153 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003154 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003155 /*BitWidth=*/0,
3156 /*Mutable=*/false);
3157 T->addDecl(Field);
3158 }
3159
Douglas Gregor838db382010-02-11 01:19:42 +00003160 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003161
3162 BlockDescriptorExtendedType = T;
3163
3164 return getTagDeclType(BlockDescriptorExtendedType);
3165}
3166
3167void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3168 const RecordType *Rec = T->getAs<RecordType>();
3169 assert(Rec && "Invalid BlockDescriptorType");
3170 BlockDescriptorExtendedType = Rec->getDecl();
3171}
3172
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003173bool ASTContext::BlockRequiresCopying(QualType Ty) {
3174 if (Ty->isBlockPointerType())
3175 return true;
3176 if (isObjCNSObjectType(Ty))
3177 return true;
3178 if (Ty->isObjCObjectPointerType())
3179 return true;
3180 return false;
3181}
3182
3183QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3184 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003185 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003186 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003187 // unsigned int __flags;
3188 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003189 // void *__copy_helper; // as needed
3190 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003191 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003192 // } *
3193
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003194 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3195
3196 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003197 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003198 llvm::SmallString<36> Name;
3199 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3200 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003201 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003202 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3203 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003204 T->startDefinition();
3205 QualType Int32Ty = IntTy;
3206 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3207 QualType FieldTypes[] = {
3208 getPointerType(VoidPtrTy),
3209 getPointerType(getTagDeclType(T)),
3210 Int32Ty,
3211 Int32Ty,
3212 getPointerType(VoidPtrTy),
3213 getPointerType(VoidPtrTy),
3214 Ty
3215 };
3216
3217 const char *FieldNames[] = {
3218 "__isa",
3219 "__forwarding",
3220 "__flags",
3221 "__size",
3222 "__copy_helper",
3223 "__destroy_helper",
3224 DeclName,
3225 };
3226
3227 for (size_t i = 0; i < 7; ++i) {
3228 if (!HasCopyAndDispose && i >=4 && i <= 5)
3229 continue;
3230 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3231 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003232 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003233 /*BitWidth=*/0, /*Mutable=*/false);
3234 T->addDecl(Field);
3235 }
3236
Douglas Gregor838db382010-02-11 01:19:42 +00003237 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003238
3239 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003240}
3241
3242
3243QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003244 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003245 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003246 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003247 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003248 llvm::SmallString<36> Name;
3249 llvm::raw_svector_ostream(Name) << "__block_literal_"
3250 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003251 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003252 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3253 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003254 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003255 QualType FieldTypes[] = {
3256 getPointerType(VoidPtrTy),
3257 IntTy,
3258 IntTy,
3259 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003260 (BlockHasCopyDispose ?
3261 getPointerType(getBlockDescriptorExtendedType()) :
3262 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003263 };
3264
3265 const char *FieldNames[] = {
3266 "__isa",
3267 "__flags",
3268 "__reserved",
3269 "__FuncPtr",
3270 "__descriptor"
3271 };
3272
3273 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003274 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003275 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003276 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003277 /*BitWidth=*/0, /*Mutable=*/false);
3278 T->addDecl(Field);
3279 }
3280
3281 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3282 const Expr *E = BlockDeclRefDecls[i];
3283 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3284 clang::IdentifierInfo *Name = 0;
3285 if (BDRE) {
3286 const ValueDecl *D = BDRE->getDecl();
3287 Name = &Idents.get(D->getName());
3288 }
3289 QualType FieldType = E->getType();
3290
3291 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003292 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3293 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003294
3295 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003296 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003297 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003298 T->addDecl(Field);
3299 }
3300
Douglas Gregor838db382010-02-11 01:19:42 +00003301 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003302
3303 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003304}
3305
Douglas Gregor319ac892009-04-23 22:29:11 +00003306void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003307 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003308 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3309 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3310}
3311
Anders Carlssone8c49532007-10-29 06:33:42 +00003312// This returns true if a type has been typedefed to BOOL:
3313// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003314static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003315 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003316 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3317 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003319 return false;
3320}
3321
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003322/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003323/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003324CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003325 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003327 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003328 if (sz.isPositive() && type->isIntegralType())
3329 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003330 // Treat arrays as pointers, since that's how they're passed in.
3331 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003332 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003333 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003334}
3335
3336static inline
3337std::string charUnitsToString(const CharUnits &CU) {
3338 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003339}
3340
David Chisnall5e530af2009-11-17 19:33:30 +00003341/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3342/// declaration.
3343void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3344 std::string& S) {
3345 const BlockDecl *Decl = Expr->getBlockDecl();
3346 QualType BlockTy =
3347 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3348 // Encode result type.
3349 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3350 // Compute size of all parameters.
3351 // Start with computing size of a pointer in number of bytes.
3352 // FIXME: There might(should) be a better way of doing this computation!
3353 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003354 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3355 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003356 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3357 E = Decl->param_end(); PI != E; ++PI) {
3358 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003359 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003360 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003361 ParmOffset += sz;
3362 }
3363 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003364 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003365 // Block pointer and offset.
3366 S += "@?0";
3367 ParmOffset = PtrSize;
3368
3369 // Argument types.
3370 ParmOffset = PtrSize;
3371 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3372 Decl->param_end(); PI != E; ++PI) {
3373 ParmVarDecl *PVDecl = *PI;
3374 QualType PType = PVDecl->getOriginalType();
3375 if (const ArrayType *AT =
3376 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3377 // Use array's original type only if it has known number of
3378 // elements.
3379 if (!isa<ConstantArrayType>(AT))
3380 PType = PVDecl->getType();
3381 } else if (PType->isFunctionType())
3382 PType = PVDecl->getType();
3383 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003384 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003385 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003386 }
3387}
3388
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003389/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003390/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003391void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003392 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003393 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003394 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003395 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003396 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003397 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003398 // Compute size of all parameters.
3399 // Start with computing size of a pointer in number of bytes.
3400 // FIXME: There might(should) be a better way of doing this computation!
3401 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003402 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003403 // The first two arguments (self and _cmd) are pointers; account for
3404 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003405 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003406 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3407 E = Decl->param_end(); PI != E; ++PI) {
3408 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003409 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003410 assert (sz.isPositive() &&
3411 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003412 ParmOffset += sz;
3413 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003414 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003415 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003416 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003418 // Argument types.
3419 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003420 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3421 E = Decl->param_end(); PI != E; ++PI) {
3422 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003423 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003424 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003425 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3426 // Use array's original type only if it has known number of
3427 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003428 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003429 PType = PVDecl->getType();
3430 } else if (PType->isFunctionType())
3431 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003432 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003433 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003434 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003435 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003436 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003437 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003438 }
3439}
3440
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003441/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003442/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003443/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3444/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003445/// Property attributes are stored as a comma-delimited C string. The simple
3446/// attributes readonly and bycopy are encoded as single characters. The
3447/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3448/// encoded as single characters, followed by an identifier. Property types
3449/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003450/// these attributes are defined by the following enumeration:
3451/// @code
3452/// enum PropertyAttributes {
3453/// kPropertyReadOnly = 'R', // property is read-only.
3454/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3455/// kPropertyByref = '&', // property is a reference to the value last assigned
3456/// kPropertyDynamic = 'D', // property is dynamic
3457/// kPropertyGetter = 'G', // followed by getter selector name
3458/// kPropertySetter = 'S', // followed by setter selector name
3459/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3460/// kPropertyType = 't' // followed by old-style type encoding.
3461/// kPropertyWeak = 'W' // 'weak' property
3462/// kPropertyStrong = 'P' // property GC'able
3463/// kPropertyNonAtomic = 'N' // property non-atomic
3464/// };
3465/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003466void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003467 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003468 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003469 // Collect information from the property implementation decl(s).
3470 bool Dynamic = false;
3471 ObjCPropertyImplDecl *SynthesizePID = 0;
3472
3473 // FIXME: Duplicated code due to poor abstraction.
3474 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003475 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003476 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3477 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003478 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003479 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003480 ObjCPropertyImplDecl *PID = *i;
3481 if (PID->getPropertyDecl() == PD) {
3482 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3483 Dynamic = true;
3484 } else {
3485 SynthesizePID = PID;
3486 }
3487 }
3488 }
3489 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003490 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003491 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003492 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003493 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003494 ObjCPropertyImplDecl *PID = *i;
3495 if (PID->getPropertyDecl() == PD) {
3496 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3497 Dynamic = true;
3498 } else {
3499 SynthesizePID = PID;
3500 }
3501 }
Mike Stump1eb44332009-09-09 15:08:12 +00003502 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003503 }
3504 }
3505
3506 // FIXME: This is not very efficient.
3507 S = "T";
3508
3509 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003510 // GCC has some special rules regarding encoding of properties which
3511 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003512 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003513 true /* outermost type */,
3514 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003515
3516 if (PD->isReadOnly()) {
3517 S += ",R";
3518 } else {
3519 switch (PD->getSetterKind()) {
3520 case ObjCPropertyDecl::Assign: break;
3521 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003522 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003523 }
3524 }
3525
3526 // It really isn't clear at all what this means, since properties
3527 // are "dynamic by default".
3528 if (Dynamic)
3529 S += ",D";
3530
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003531 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3532 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003534 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3535 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003536 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003537 }
3538
3539 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3540 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003541 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003542 }
3543
3544 if (SynthesizePID) {
3545 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3546 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003547 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003548 }
3549
3550 // FIXME: OBJCGC: weak & strong
3551}
3552
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003553/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003554/// Another legacy compatibility encoding: 32-bit longs are encoded as
3555/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003556/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3557///
3558void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003559 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003560 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003561 if (BT->getKind() == BuiltinType::ULong &&
3562 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003563 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003564 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003565 if (BT->getKind() == BuiltinType::Long &&
3566 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003567 PointeeTy = IntTy;
3568 }
3569 }
3570}
3571
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003572void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003573 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003574 // We follow the behavior of gcc, expanding structures which are
3575 // directly pointed to, and expanding embedded structures. Note that
3576 // these rules are sufficient to prevent recursive encoding of the
3577 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003578 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003579 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003580}
3581
Mike Stump1eb44332009-09-09 15:08:12 +00003582static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003583 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003584 const Expr *E = FD->getBitWidth();
3585 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3586 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003587 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003588 S += 'b';
3589 S += llvm::utostr(N);
3590}
3591
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003592// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003593void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3594 bool ExpandPointedToStructures,
3595 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003596 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003597 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003598 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003599 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003600 if (FD && FD->isBitField())
3601 return EncodeBitField(this, S, FD);
3602 char encoding;
3603 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003604 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003605 case BuiltinType::Void: encoding = 'v'; break;
3606 case BuiltinType::Bool: encoding = 'B'; break;
3607 case BuiltinType::Char_U:
3608 case BuiltinType::UChar: encoding = 'C'; break;
3609 case BuiltinType::UShort: encoding = 'S'; break;
3610 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003611 case BuiltinType::ULong:
3612 encoding =
3613 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003614 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003615 case BuiltinType::UInt128: encoding = 'T'; break;
3616 case BuiltinType::ULongLong: encoding = 'Q'; break;
3617 case BuiltinType::Char_S:
3618 case BuiltinType::SChar: encoding = 'c'; break;
3619 case BuiltinType::Short: encoding = 's'; break;
3620 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003621 case BuiltinType::Long:
3622 encoding =
3623 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003624 break;
3625 case BuiltinType::LongLong: encoding = 'q'; break;
3626 case BuiltinType::Int128: encoding = 't'; break;
3627 case BuiltinType::Float: encoding = 'f'; break;
3628 case BuiltinType::Double: encoding = 'd'; break;
3629 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003630 }
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003632 S += encoding;
3633 return;
3634 }
Mike Stump1eb44332009-09-09 15:08:12 +00003635
John McCall183700f2009-09-21 23:43:11 +00003636 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003637 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003638 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003639 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003640 return;
3641 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003642
Ted Kremenek6217b802009-07-29 21:53:49 +00003643 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003644 if (PT->isObjCSelType()) {
3645 S += ':';
3646 return;
3647 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003648 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003649
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003650 bool isReadOnly = false;
3651 // For historical/compatibility reasons, the read-only qualifier of the
3652 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3653 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003654 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003655 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003656 if (OutermostType && T.isConstQualified()) {
3657 isReadOnly = true;
3658 S += 'r';
3659 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003660 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003661 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003662 while (P->getAs<PointerType>())
3663 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003664 if (P.isConstQualified()) {
3665 isReadOnly = true;
3666 S += 'r';
3667 }
3668 }
3669 if (isReadOnly) {
3670 // Another legacy compatibility encoding. Some ObjC qualifier and type
3671 // combinations need to be rearranged.
3672 // Rewrite "in const" from "nr" to "rn"
3673 const char * s = S.c_str();
3674 int len = S.length();
3675 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3676 std::string replace = "rn";
3677 S.replace(S.end()-2, S.end(), replace);
3678 }
3679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003681 if (PointeeTy->isCharType()) {
3682 // char pointer types should be encoded as '*' unless it is a
3683 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003684 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003685 S += '*';
3686 return;
3687 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003688 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003689 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3690 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3691 S += '#';
3692 return;
3693 }
3694 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3695 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3696 S += '@';
3697 return;
3698 }
3699 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003700 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003701 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003702 getLegacyIntegralTypeEncoding(PointeeTy);
3703
Mike Stump1eb44332009-09-09 15:08:12 +00003704 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003705 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003706 return;
3707 }
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003709 if (const ArrayType *AT =
3710 // Ignore type qualifiers etc.
3711 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003712 if (isa<IncompleteArrayType>(AT)) {
3713 // Incomplete arrays are encoded as a pointer to the array element.
3714 S += '^';
3715
Mike Stump1eb44332009-09-09 15:08:12 +00003716 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003717 false, ExpandStructures, FD);
3718 } else {
3719 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Anders Carlsson559a8332009-02-22 01:38:57 +00003721 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3722 S += llvm::utostr(CAT->getSize().getZExtValue());
3723 else {
3724 //Variable length arrays are encoded as a regular array with 0 elements.
3725 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3726 S += '0';
3727 }
Mike Stump1eb44332009-09-09 15:08:12 +00003728
3729 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003730 false, ExpandStructures, FD);
3731 S += ']';
3732 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003733 return;
3734 }
Mike Stump1eb44332009-09-09 15:08:12 +00003735
John McCall183700f2009-09-21 23:43:11 +00003736 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003737 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003738 return;
3739 }
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Ted Kremenek6217b802009-07-29 21:53:49 +00003741 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003742 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003743 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003744 // Anonymous structures print as '?'
3745 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3746 S += II->getName();
3747 } else {
3748 S += '?';
3749 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003750 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003751 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003752 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3753 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003754 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003755 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003756 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003757 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003758 S += '"';
3759 }
Mike Stump1eb44332009-09-09 15:08:12 +00003760
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003761 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003762 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003763 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003764 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003765 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003766 QualType qt = Field->getType();
3767 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003768 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003769 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003770 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003771 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003772 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003773 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003774 return;
3775 }
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003777 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003778 if (FD && FD->isBitField())
3779 EncodeBitField(this, S, FD);
3780 else
3781 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003782 return;
3783 }
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003785 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003786 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003787 return;
3788 }
Mike Stump1eb44332009-09-09 15:08:12 +00003789
John McCall0953e762009-09-24 19:53:00 +00003790 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003791 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003792 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003793 S += '{';
3794 const IdentifierInfo *II = OI->getIdentifier();
3795 S += II->getName();
3796 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003797 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003798 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003799 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003800 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003801 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003802 RecFields[i]);
3803 else
Mike Stump1eb44332009-09-09 15:08:12 +00003804 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003805 FD);
3806 }
3807 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003808 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003809 }
Mike Stump1eb44332009-09-09 15:08:12 +00003810
John McCall183700f2009-09-21 23:43:11 +00003811 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003812 if (OPT->isObjCIdType()) {
3813 S += '@';
3814 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003815 }
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Steve Naroff27d20a22009-10-28 22:03:49 +00003817 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3818 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3819 // Since this is a binary compatibility issue, need to consult with runtime
3820 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003821 S += '#';
3822 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003823 }
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003825 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003826 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003827 ExpandPointedToStructures,
3828 ExpandStructures, FD);
3829 if (FD || EncodingProperty) {
3830 // Note that we do extended encoding of protocol qualifer list
3831 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003832 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003833 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3834 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003835 S += '<';
3836 S += (*I)->getNameAsString();
3837 S += '>';
3838 }
3839 S += '"';
3840 }
3841 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003842 }
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003844 QualType PointeeTy = OPT->getPointeeType();
3845 if (!EncodingProperty &&
3846 isa<TypedefType>(PointeeTy.getTypePtr())) {
3847 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003848 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003849 // {...};
3850 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003851 getObjCEncodingForTypeImpl(PointeeTy, S,
3852 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003853 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003854 return;
3855 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003856
3857 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003858 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003859 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003860 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003861 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3862 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003863 S += '<';
3864 S += (*I)->getNameAsString();
3865 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003866 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003867 S += '"';
3868 }
3869 return;
3870 }
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003872 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003873}
3874
Mike Stump1eb44332009-09-09 15:08:12 +00003875void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003876 std::string& S) const {
3877 if (QT & Decl::OBJC_TQ_In)
3878 S += 'n';
3879 if (QT & Decl::OBJC_TQ_Inout)
3880 S += 'N';
3881 if (QT & Decl::OBJC_TQ_Out)
3882 S += 'o';
3883 if (QT & Decl::OBJC_TQ_Bycopy)
3884 S += 'O';
3885 if (QT & Decl::OBJC_TQ_Byref)
3886 S += 'R';
3887 if (QT & Decl::OBJC_TQ_Oneway)
3888 S += 'V';
3889}
3890
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003891void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003892 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003894 BuiltinVaListType = T;
3895}
3896
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003897void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003898 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003899}
3900
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003901void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003902 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003903}
3904
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003905void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003906 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003907}
3908
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003909void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003910 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003911}
3912
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003913void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003914 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003915 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003917 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003918}
3919
John McCall0bd6feb2009-12-02 08:04:21 +00003920/// \brief Retrieve the template name that corresponds to a non-empty
3921/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003922TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3923 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003924 unsigned size = End - Begin;
3925 assert(size > 1 && "set is not overloaded!");
3926
3927 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3928 size * sizeof(FunctionTemplateDecl*));
3929 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3930
3931 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003932 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003933 NamedDecl *D = *I;
3934 assert(isa<FunctionTemplateDecl>(D) ||
3935 (isa<UsingShadowDecl>(D) &&
3936 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3937 *Storage++ = D;
3938 }
3939
3940 return TemplateName(OT);
3941}
3942
Douglas Gregor7532dc62009-03-30 22:58:21 +00003943/// \brief Retrieve the template name that represents a qualified
3944/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003945TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003946 bool TemplateKeyword,
3947 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003948 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003949 llvm::FoldingSetNodeID ID;
3950 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3951
3952 void *InsertPos = 0;
3953 QualifiedTemplateName *QTN =
3954 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3955 if (!QTN) {
3956 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3957 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3958 }
3959
3960 return TemplateName(QTN);
3961}
3962
3963/// \brief Retrieve the template name that represents a dependent
3964/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003965TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003966 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003967 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003968 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003969
3970 llvm::FoldingSetNodeID ID;
3971 DependentTemplateName::Profile(ID, NNS, Name);
3972
3973 void *InsertPos = 0;
3974 DependentTemplateName *QTN =
3975 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3976
3977 if (QTN)
3978 return TemplateName(QTN);
3979
3980 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3981 if (CanonNNS == NNS) {
3982 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3983 } else {
3984 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3985 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003986 DependentTemplateName *CheckQTN =
3987 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3988 assert(!CheckQTN && "Dependent type name canonicalization broken");
3989 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003990 }
3991
3992 DependentTemplateNames.InsertNode(QTN, InsertPos);
3993 return TemplateName(QTN);
3994}
3995
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003996/// \brief Retrieve the template name that represents a dependent
3997/// template name such as \c MetaFun::template operator+.
3998TemplateName
3999ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4000 OverloadedOperatorKind Operator) {
4001 assert((!NNS || NNS->isDependent()) &&
4002 "Nested name specifier must be dependent");
4003
4004 llvm::FoldingSetNodeID ID;
4005 DependentTemplateName::Profile(ID, NNS, Operator);
4006
4007 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004008 DependentTemplateName *QTN
4009 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004010
4011 if (QTN)
4012 return TemplateName(QTN);
4013
4014 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4015 if (CanonNNS == NNS) {
4016 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4017 } else {
4018 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4019 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004020
4021 DependentTemplateName *CheckQTN
4022 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4023 assert(!CheckQTN && "Dependent template name canonicalization broken");
4024 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004025 }
4026
4027 DependentTemplateNames.InsertNode(QTN, InsertPos);
4028 return TemplateName(QTN);
4029}
4030
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004031/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004032/// TargetInfo, produce the corresponding type. The unsigned @p Type
4033/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004034CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004035 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004036 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004037 case TargetInfo::SignedShort: return ShortTy;
4038 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4039 case TargetInfo::SignedInt: return IntTy;
4040 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4041 case TargetInfo::SignedLong: return LongTy;
4042 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4043 case TargetInfo::SignedLongLong: return LongLongTy;
4044 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4045 }
4046
4047 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004048 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004049}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004050
4051//===----------------------------------------------------------------------===//
4052// Type Predicates.
4053//===----------------------------------------------------------------------===//
4054
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004055/// isObjCNSObjectType - Return true if this is an NSObject object using
4056/// NSObject attribute on a c-style pointer type.
4057/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004058/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004059///
4060bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4061 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4062 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004063 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004064 return true;
4065 }
Mike Stump1eb44332009-09-09 15:08:12 +00004066 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004067}
4068
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004069/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4070/// garbage collection attribute.
4071///
John McCall0953e762009-09-24 19:53:00 +00004072Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4073 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004074 if (getLangOptions().ObjC1 &&
4075 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004076 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004077 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004078 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004079 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004080 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004081 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004082 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004083 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004084 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004085 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004086 // Non-pointers have none gc'able attribute regardless of the attribute
4087 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004088 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004089 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004090 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004091 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004092}
4093
Chris Lattner6ac46a42008-04-07 06:51:04 +00004094//===----------------------------------------------------------------------===//
4095// Type Compatibility Testing
4096//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004097
Mike Stump1eb44332009-09-09 15:08:12 +00004098/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004099/// compatible.
4100static bool areCompatVectorTypes(const VectorType *LHS,
4101 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004102 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004103 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004104 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004105}
4106
Steve Naroff4084c302009-07-23 01:01:38 +00004107//===----------------------------------------------------------------------===//
4108// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4109//===----------------------------------------------------------------------===//
4110
4111/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4112/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004113bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4114 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004115 if (lProto == rProto)
4116 return true;
4117 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4118 E = rProto->protocol_end(); PI != E; ++PI)
4119 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4120 return true;
4121 return false;
4122}
4123
Steve Naroff4084c302009-07-23 01:01:38 +00004124/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4125/// return true if lhs's protocols conform to rhs's protocol; false
4126/// otherwise.
4127bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4128 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4129 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4130 return false;
4131}
4132
4133/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4134/// ObjCQualifiedIDType.
4135bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4136 bool compare) {
4137 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004138 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004139 lhs->isObjCIdType() || lhs->isObjCClassType())
4140 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004141 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004142 rhs->isObjCIdType() || rhs->isObjCClassType())
4143 return true;
4144
4145 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004146 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Steve Naroff4084c302009-07-23 01:01:38 +00004148 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Steve Naroff4084c302009-07-23 01:01:38 +00004150 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004151 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004152 // make sure we check the class hierarchy.
4153 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4154 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4155 E = lhsQID->qual_end(); I != E; ++I) {
4156 // when comparing an id<P> on lhs with a static type on rhs,
4157 // see if static class implements all of id's protocols, directly or
4158 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004159 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004160 return false;
4161 }
4162 }
4163 // If there are no qualifiers and no interface, we have an 'id'.
4164 return true;
4165 }
Mike Stump1eb44332009-09-09 15:08:12 +00004166 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004167 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4168 E = lhsQID->qual_end(); I != E; ++I) {
4169 ObjCProtocolDecl *lhsProto = *I;
4170 bool match = false;
4171
4172 // when comparing an id<P> on lhs with a static type on rhs,
4173 // see if static class implements all of id's protocols, directly or
4174 // through its super class and categories.
4175 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4176 E = rhsOPT->qual_end(); J != E; ++J) {
4177 ObjCProtocolDecl *rhsProto = *J;
4178 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4179 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4180 match = true;
4181 break;
4182 }
4183 }
Mike Stump1eb44332009-09-09 15:08:12 +00004184 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004185 // make sure we check the class hierarchy.
4186 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4187 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4188 E = lhsQID->qual_end(); I != E; ++I) {
4189 // when comparing an id<P> on lhs with a static type on rhs,
4190 // see if static class implements all of id's protocols, directly or
4191 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004192 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004193 match = true;
4194 break;
4195 }
4196 }
4197 }
4198 if (!match)
4199 return false;
4200 }
Mike Stump1eb44332009-09-09 15:08:12 +00004201
Steve Naroff4084c302009-07-23 01:01:38 +00004202 return true;
4203 }
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Steve Naroff4084c302009-07-23 01:01:38 +00004205 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4206 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4207
Mike Stump1eb44332009-09-09 15:08:12 +00004208 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004209 lhs->getAsObjCInterfacePointerType()) {
4210 if (lhsOPT->qual_empty()) {
4211 bool match = false;
4212 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4213 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4214 E = rhsQID->qual_end(); I != E; ++I) {
4215 // when comparing an id<P> on lhs with a static type on rhs,
4216 // see if static class implements all of id's protocols, directly or
4217 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004218 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004219 match = true;
4220 break;
4221 }
4222 }
4223 if (!match)
4224 return false;
4225 }
4226 return true;
4227 }
Mike Stump1eb44332009-09-09 15:08:12 +00004228 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004229 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4230 E = lhsOPT->qual_end(); I != E; ++I) {
4231 ObjCProtocolDecl *lhsProto = *I;
4232 bool match = false;
4233
4234 // when comparing an id<P> on lhs with a static type on rhs,
4235 // see if static class implements all of id's protocols, directly or
4236 // through its super class and categories.
4237 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4238 E = rhsQID->qual_end(); J != E; ++J) {
4239 ObjCProtocolDecl *rhsProto = *J;
4240 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4241 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4242 match = true;
4243 break;
4244 }
4245 }
4246 if (!match)
4247 return false;
4248 }
4249 return true;
4250 }
4251 return false;
4252}
4253
Eli Friedman3d815e72008-08-22 00:56:42 +00004254/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004255/// compatible for assignment from RHS to LHS. This handles validation of any
4256/// protocol qualifiers on the LHS or RHS.
4257///
Steve Naroff14108da2009-07-10 23:34:53 +00004258bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4259 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004260 // If either type represents the built-in 'id' or 'Class' types, return true.
4261 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004262 return true;
4263
Steve Naroff4084c302009-07-23 01:01:38 +00004264 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004265 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4266 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004267 false);
4268
Steve Naroff14108da2009-07-10 23:34:53 +00004269 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4270 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004271 if (LHS && RHS) // We have 2 user-defined types.
4272 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Steve Naroff4084c302009-07-23 01:01:38 +00004274 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004275}
4276
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004277/// getIntersectionOfProtocols - This routine finds the intersection of set
4278/// of protocols inherited from two distinct objective-c pointer objects.
4279/// It is used to build composite qualifier list of the composite type of
4280/// the conditional expression involving two objective-c pointer objects.
4281static
4282void getIntersectionOfProtocols(ASTContext &Context,
4283 const ObjCObjectPointerType *LHSOPT,
4284 const ObjCObjectPointerType *RHSOPT,
4285 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4286
4287 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4288 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4289
4290 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4291 unsigned LHSNumProtocols = LHS->getNumProtocols();
4292 if (LHSNumProtocols > 0)
4293 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4294 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004295 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4296 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004297 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4298 LHSInheritedProtocols.end());
4299 }
4300
4301 unsigned RHSNumProtocols = RHS->getNumProtocols();
4302 if (RHSNumProtocols > 0) {
4303 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4304 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4305 if (InheritedProtocolSet.count(RHSProtocols[i]))
4306 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4307 }
4308 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004309 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004310 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004311 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4312 RHSInheritedProtocols.begin(),
4313 E = RHSInheritedProtocols.end(); I != E; ++I)
4314 if (InheritedProtocolSet.count((*I)))
4315 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004316 }
4317}
4318
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004319/// areCommonBaseCompatible - Returns common base class of the two classes if
4320/// one found. Note that this is O'2 algorithm. But it will be called as the
4321/// last type comparison in a ?-exp of ObjC pointer types before a
4322/// warning is issued. So, its invokation is extremely rare.
4323QualType ASTContext::areCommonBaseCompatible(
4324 const ObjCObjectPointerType *LHSOPT,
4325 const ObjCObjectPointerType *RHSOPT) {
4326 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4327 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4328 if (!LHS || !RHS)
4329 return QualType();
4330
4331 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4332 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4333 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004334 if (canAssignObjCInterfaces(LHS, RHS)) {
4335 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4336 getIntersectionOfProtocols(*this,
4337 LHSOPT, RHSOPT, IntersectionOfProtocols);
4338 if (IntersectionOfProtocols.empty())
4339 LHSTy = getObjCObjectPointerType(LHSTy);
4340 else
4341 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4342 IntersectionOfProtocols.size());
4343 return LHSTy;
4344 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004345 }
4346
4347 return QualType();
4348}
4349
Eli Friedman3d815e72008-08-22 00:56:42 +00004350bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4351 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004352 // Verify that the base decls are compatible: the RHS must be a subclass of
4353 // the LHS.
4354 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4355 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Chris Lattner6ac46a42008-04-07 06:51:04 +00004357 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4358 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004359 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004360 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Chris Lattner6ac46a42008-04-07 06:51:04 +00004362 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4363 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004364 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004365 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004367 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4368 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004369 LHSPI != LHSPE; LHSPI++) {
4370 bool RHSImplementsProtocol = false;
4371
4372 // If the RHS doesn't implement the protocol on the left, the types
4373 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004374 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004375 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004376 RHSPI != RHSPE; RHSPI++) {
4377 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004378 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004379 break;
4380 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004381 }
4382 // FIXME: For better diagnostics, consider passing back the protocol name.
4383 if (!RHSImplementsProtocol)
4384 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004385 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004386 // The RHS implements all protocols listed on the LHS.
4387 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004388}
4389
Steve Naroff389bf462009-02-12 17:52:19 +00004390bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4391 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004392 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4393 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Steve Naroff14108da2009-07-10 23:34:53 +00004395 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004396 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004397
4398 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4399 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004400}
4401
Mike Stump1eb44332009-09-09 15:08:12 +00004402/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004403/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004404/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004405/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004406bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004407 if (getLangOptions().CPlusPlus)
4408 return hasSameType(LHS, RHS);
4409
Eli Friedman3d815e72008-08-22 00:56:42 +00004410 return !mergeTypes(LHS, RHS).isNull();
4411}
4412
4413QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004414 const FunctionType *lbase = lhs->getAs<FunctionType>();
4415 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004416 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4417 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004418 bool allLTypes = true;
4419 bool allRTypes = true;
4420
4421 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004422 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004423 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004424 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004425 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004426 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004427 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004428 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004429 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4430 if (NoReturn != lbase->getNoReturnAttr())
4431 allLTypes = false;
4432 if (NoReturn != rbase->getNoReturnAttr())
4433 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004434 CallingConv lcc = lbase->getCallConv();
4435 CallingConv rcc = rbase->getCallConv();
4436 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004437 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004438 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Eli Friedman3d815e72008-08-22 00:56:42 +00004440 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004441 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4442 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004443 unsigned lproto_nargs = lproto->getNumArgs();
4444 unsigned rproto_nargs = rproto->getNumArgs();
4445
4446 // Compatible functions must have the same number of arguments
4447 if (lproto_nargs != rproto_nargs)
4448 return QualType();
4449
4450 // Variadic and non-variadic functions aren't compatible
4451 if (lproto->isVariadic() != rproto->isVariadic())
4452 return QualType();
4453
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004454 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4455 return QualType();
4456
Eli Friedman3d815e72008-08-22 00:56:42 +00004457 // Check argument compatibility
4458 llvm::SmallVector<QualType, 10> types;
4459 for (unsigned i = 0; i < lproto_nargs; i++) {
4460 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4461 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4462 QualType argtype = mergeTypes(largtype, rargtype);
4463 if (argtype.isNull()) return QualType();
4464 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004465 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4466 allLTypes = false;
4467 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4468 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004469 }
4470 if (allLTypes) return lhs;
4471 if (allRTypes) return rhs;
4472 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004473 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004474 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004475 }
4476
4477 if (lproto) allRTypes = false;
4478 if (rproto) allLTypes = false;
4479
Douglas Gregor72564e72009-02-26 23:50:07 +00004480 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004481 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004482 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004483 if (proto->isVariadic()) return QualType();
4484 // Check that the types are compatible with the types that
4485 // would result from default argument promotions (C99 6.7.5.3p15).
4486 // The only types actually affected are promotable integer
4487 // types and floats, which would be passed as a different
4488 // type depending on whether the prototype is visible.
4489 unsigned proto_nargs = proto->getNumArgs();
4490 for (unsigned i = 0; i < proto_nargs; ++i) {
4491 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004492
4493 // Look at the promotion type of enum types, since that is the type used
4494 // to pass enum values.
4495 if (const EnumType *Enum = argTy->getAs<EnumType>())
4496 argTy = Enum->getDecl()->getPromotionType();
4497
Eli Friedman3d815e72008-08-22 00:56:42 +00004498 if (argTy->isPromotableIntegerType() ||
4499 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4500 return QualType();
4501 }
4502
4503 if (allLTypes) return lhs;
4504 if (allRTypes) return rhs;
4505 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004506 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004507 proto->getTypeQuals(),
4508 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004509 }
4510
4511 if (allLTypes) return lhs;
4512 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004513 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004514}
4515
4516QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004517 // C++ [expr]: If an expression initially has the type "reference to T", the
4518 // type is adjusted to "T" prior to any further analysis, the expression
4519 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004520 // expression is an lvalue unless the reference is an rvalue reference and
4521 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004522 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4523 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4524
Eli Friedman3d815e72008-08-22 00:56:42 +00004525 QualType LHSCan = getCanonicalType(LHS),
4526 RHSCan = getCanonicalType(RHS);
4527
4528 // If two types are identical, they are compatible.
4529 if (LHSCan == RHSCan)
4530 return LHS;
4531
John McCall0953e762009-09-24 19:53:00 +00004532 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004533 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4534 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004535 if (LQuals != RQuals) {
4536 // If any of these qualifiers are different, we have a type
4537 // mismatch.
4538 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4539 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4540 return QualType();
4541
4542 // Exactly one GC qualifier difference is allowed: __strong is
4543 // okay if the other type has no GC qualifier but is an Objective
4544 // C object pointer (i.e. implicitly strong by default). We fix
4545 // this by pretending that the unqualified type was actually
4546 // qualified __strong.
4547 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4548 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4549 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4550
4551 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4552 return QualType();
4553
4554 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4555 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4556 }
4557 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4558 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4559 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004560 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004561 }
4562
4563 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004564
Eli Friedman852d63b2009-06-01 01:22:52 +00004565 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4566 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004567
Chris Lattner1adb8832008-01-14 05:45:46 +00004568 // We want to consider the two function types to be the same for these
4569 // comparisons, just force one to the other.
4570 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4571 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004572
4573 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004574 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4575 LHSClass = Type::ConstantArray;
4576 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4577 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004578
Nate Begeman213541a2008-04-18 23:10:10 +00004579 // Canonicalize ExtVector -> Vector.
4580 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4581 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004582
Chris Lattnera36a61f2008-04-07 05:43:21 +00004583 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004584 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004585 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004586 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004587 // Compatibility is based on the underlying type, not the promotion
4588 // type.
John McCall183700f2009-09-21 23:43:11 +00004589 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004590 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4591 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004592 }
John McCall183700f2009-09-21 23:43:11 +00004593 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004594 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4595 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004596 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004597
Eli Friedman3d815e72008-08-22 00:56:42 +00004598 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004599 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004600
Steve Naroff4a746782008-01-09 22:43:08 +00004601 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004602 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004603#define TYPE(Class, Base)
4604#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004605#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004606#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4607#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4608#include "clang/AST/TypeNodes.def"
4609 assert(false && "Non-canonical and dependent types shouldn't get here");
4610 return QualType();
4611
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004612 case Type::LValueReference:
4613 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004614 case Type::MemberPointer:
4615 assert(false && "C++ should never be in mergeTypes");
4616 return QualType();
4617
4618 case Type::IncompleteArray:
4619 case Type::VariableArray:
4620 case Type::FunctionProto:
4621 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004622 assert(false && "Types are eliminated above");
4623 return QualType();
4624
Chris Lattner1adb8832008-01-14 05:45:46 +00004625 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004626 {
4627 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004628 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4629 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004630 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4631 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004632 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004633 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004634 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004635 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004636 return getPointerType(ResultType);
4637 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004638 case Type::BlockPointer:
4639 {
4640 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004641 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4642 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004643 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4644 if (ResultType.isNull()) return QualType();
4645 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4646 return LHS;
4647 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4648 return RHS;
4649 return getBlockPointerType(ResultType);
4650 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004651 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004652 {
4653 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4654 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4655 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4656 return QualType();
4657
4658 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4659 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4660 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4661 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004662 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4663 return LHS;
4664 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4665 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004666 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4667 ArrayType::ArraySizeModifier(), 0);
4668 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4669 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004670 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4671 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004672 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4673 return LHS;
4674 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4675 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004676 if (LVAT) {
4677 // FIXME: This isn't correct! But tricky to implement because
4678 // the array's size has to be the size of LHS, but the type
4679 // has to be different.
4680 return LHS;
4681 }
4682 if (RVAT) {
4683 // FIXME: This isn't correct! But tricky to implement because
4684 // the array's size has to be the size of RHS, but the type
4685 // has to be different.
4686 return RHS;
4687 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004688 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4689 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004690 return getIncompleteArrayType(ResultType,
4691 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004692 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004693 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004694 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004695 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004696 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004697 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004698 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004699 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004700 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004701 case Type::Complex:
4702 // Distinct complex types are incompatible.
4703 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004704 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004705 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004706 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004707 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004708 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004709 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004710 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004711 // FIXME: This should be type compatibility, e.g. whether
4712 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004713 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4714 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004715 if (LHSIface && RHSIface &&
4716 canAssignObjCInterfaces(LHSIface, RHSIface))
4717 return LHS;
4718
Eli Friedman3d815e72008-08-22 00:56:42 +00004719 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004720 }
Steve Naroff14108da2009-07-10 23:34:53 +00004721 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004722 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4723 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004724 return LHS;
4725
Steve Naroffbc76dd02008-12-10 22:14:21 +00004726 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004727 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004728 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004729
4730 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004731}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004732
Chris Lattner5426bf62008-04-07 07:01:58 +00004733//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004734// Integer Predicates
4735//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004736
Eli Friedmanad74a752008-06-28 06:23:08 +00004737unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004738 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004739 return 1;
John McCall842aef82009-12-09 09:09:27 +00004740 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004741 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004742 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004743 return (unsigned)getTypeSize(T);
4744}
4745
4746QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4747 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004748
4749 // Turn <4 x signed int> -> <4 x unsigned int>
4750 if (const VectorType *VTy = T->getAs<VectorType>())
4751 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004752 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004753
4754 // For enums, we return the unsigned version of the base type.
4755 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004756 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004757
4758 const BuiltinType *BTy = T->getAs<BuiltinType>();
4759 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004760 switch (BTy->getKind()) {
4761 case BuiltinType::Char_S:
4762 case BuiltinType::SChar:
4763 return UnsignedCharTy;
4764 case BuiltinType::Short:
4765 return UnsignedShortTy;
4766 case BuiltinType::Int:
4767 return UnsignedIntTy;
4768 case BuiltinType::Long:
4769 return UnsignedLongTy;
4770 case BuiltinType::LongLong:
4771 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004772 case BuiltinType::Int128:
4773 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004774 default:
4775 assert(0 && "Unexpected signed integer type");
4776 return QualType();
4777 }
4778}
4779
Douglas Gregor2cf26342009-04-09 22:27:44 +00004780ExternalASTSource::~ExternalASTSource() { }
4781
4782void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004783
4784
4785//===----------------------------------------------------------------------===//
4786// Builtin Type Computation
4787//===----------------------------------------------------------------------===//
4788
4789/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4790/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004791static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004792 ASTContext::GetBuiltinTypeError &Error,
4793 bool AllowTypeModifiers = true) {
4794 // Modifiers.
4795 int HowLong = 0;
4796 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004797
Chris Lattner86df27b2009-06-14 00:45:47 +00004798 // Read the modifiers first.
4799 bool Done = false;
4800 while (!Done) {
4801 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004802 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004803 case 'S':
4804 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4805 assert(!Signed && "Can't use 'S' modifier multiple times!");
4806 Signed = true;
4807 break;
4808 case 'U':
4809 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4810 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4811 Unsigned = true;
4812 break;
4813 case 'L':
4814 assert(HowLong <= 2 && "Can't have LLLL modifier");
4815 ++HowLong;
4816 break;
4817 }
4818 }
4819
4820 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004821
Chris Lattner86df27b2009-06-14 00:45:47 +00004822 // Read the base type.
4823 switch (*Str++) {
4824 default: assert(0 && "Unknown builtin type letter!");
4825 case 'v':
4826 assert(HowLong == 0 && !Signed && !Unsigned &&
4827 "Bad modifiers used with 'v'!");
4828 Type = Context.VoidTy;
4829 break;
4830 case 'f':
4831 assert(HowLong == 0 && !Signed && !Unsigned &&
4832 "Bad modifiers used with 'f'!");
4833 Type = Context.FloatTy;
4834 break;
4835 case 'd':
4836 assert(HowLong < 2 && !Signed && !Unsigned &&
4837 "Bad modifiers used with 'd'!");
4838 if (HowLong)
4839 Type = Context.LongDoubleTy;
4840 else
4841 Type = Context.DoubleTy;
4842 break;
4843 case 's':
4844 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4845 if (Unsigned)
4846 Type = Context.UnsignedShortTy;
4847 else
4848 Type = Context.ShortTy;
4849 break;
4850 case 'i':
4851 if (HowLong == 3)
4852 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4853 else if (HowLong == 2)
4854 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4855 else if (HowLong == 1)
4856 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4857 else
4858 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4859 break;
4860 case 'c':
4861 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4862 if (Signed)
4863 Type = Context.SignedCharTy;
4864 else if (Unsigned)
4865 Type = Context.UnsignedCharTy;
4866 else
4867 Type = Context.CharTy;
4868 break;
4869 case 'b': // boolean
4870 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4871 Type = Context.BoolTy;
4872 break;
4873 case 'z': // size_t.
4874 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4875 Type = Context.getSizeType();
4876 break;
4877 case 'F':
4878 Type = Context.getCFConstantStringType();
4879 break;
4880 case 'a':
4881 Type = Context.getBuiltinVaListType();
4882 assert(!Type.isNull() && "builtin va list type not initialized!");
4883 break;
4884 case 'A':
4885 // This is a "reference" to a va_list; however, what exactly
4886 // this means depends on how va_list is defined. There are two
4887 // different kinds of va_list: ones passed by value, and ones
4888 // passed by reference. An example of a by-value va_list is
4889 // x86, where va_list is a char*. An example of by-ref va_list
4890 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4891 // we want this argument to be a char*&; for x86-64, we want
4892 // it to be a __va_list_tag*.
4893 Type = Context.getBuiltinVaListType();
4894 assert(!Type.isNull() && "builtin va list type not initialized!");
4895 if (Type->isArrayType()) {
4896 Type = Context.getArrayDecayedType(Type);
4897 } else {
4898 Type = Context.getLValueReferenceType(Type);
4899 }
4900 break;
4901 case 'V': {
4902 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004903 unsigned NumElements = strtoul(Str, &End, 10);
4904 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004905
Chris Lattner86df27b2009-06-14 00:45:47 +00004906 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Chris Lattner86df27b2009-06-14 00:45:47 +00004908 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004909 // FIXME: Don't know what to do about AltiVec.
4910 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004911 break;
4912 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004913 case 'X': {
4914 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4915 Type = Context.getComplexType(ElementType);
4916 break;
4917 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004918 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004919 Type = Context.getFILEType();
4920 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004921 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004922 return QualType();
4923 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004924 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004925 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004926 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004927 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004928 else
4929 Type = Context.getjmp_bufType();
4930
Mike Stumpfd612db2009-07-28 23:47:15 +00004931 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004932 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004933 return QualType();
4934 }
4935 break;
Mike Stump782fa302009-07-28 02:25:19 +00004936 }
Mike Stump1eb44332009-09-09 15:08:12 +00004937
Chris Lattner86df27b2009-06-14 00:45:47 +00004938 if (!AllowTypeModifiers)
4939 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Chris Lattner86df27b2009-06-14 00:45:47 +00004941 Done = false;
4942 while (!Done) {
4943 switch (*Str++) {
4944 default: Done = true; --Str; break;
4945 case '*':
4946 Type = Context.getPointerType(Type);
4947 break;
4948 case '&':
4949 Type = Context.getLValueReferenceType(Type);
4950 break;
4951 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4952 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004953 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004954 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004955 case 'D':
4956 Type = Context.getVolatileType(Type);
4957 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004958 }
4959 }
Mike Stump1eb44332009-09-09 15:08:12 +00004960
Chris Lattner86df27b2009-06-14 00:45:47 +00004961 return Type;
4962}
4963
4964/// GetBuiltinType - Return the type for the specified builtin.
4965QualType ASTContext::GetBuiltinType(unsigned id,
4966 GetBuiltinTypeError &Error) {
4967 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004968
Chris Lattner86df27b2009-06-14 00:45:47 +00004969 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004970
Chris Lattner86df27b2009-06-14 00:45:47 +00004971 Error = GE_None;
4972 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4973 if (Error != GE_None)
4974 return QualType();
4975 while (TypeStr[0] && TypeStr[0] != '.') {
4976 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4977 if (Error != GE_None)
4978 return QualType();
4979
4980 // Do array -> pointer decay. The builtin should use the decayed type.
4981 if (Ty->isArrayType())
4982 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004983
Chris Lattner86df27b2009-06-14 00:45:47 +00004984 ArgTypes.push_back(Ty);
4985 }
4986
4987 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4988 "'.' should only occur at end of builtin type list!");
4989
4990 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4991 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4992 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00004993
4994 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00004995 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004996 TypeStr[0] == '.', 0, false, false, 0, 0,
4997 false, CC_Default);
Chris Lattner86df27b2009-06-14 00:45:47 +00004998}
Eli Friedmana95d7572009-08-19 07:44:53 +00004999
5000QualType
5001ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5002 // Perform the usual unary conversions. We do this early so that
5003 // integral promotions to "int" can allow us to exit early, in the
5004 // lhs == rhs check. Also, for conversion purposes, we ignore any
5005 // qualifiers. For example, "const float" and "float" are
5006 // equivalent.
5007 if (lhs->isPromotableIntegerType())
5008 lhs = getPromotedIntegerType(lhs);
5009 else
5010 lhs = lhs.getUnqualifiedType();
5011 if (rhs->isPromotableIntegerType())
5012 rhs = getPromotedIntegerType(rhs);
5013 else
5014 rhs = rhs.getUnqualifiedType();
5015
5016 // If both types are identical, no conversion is needed.
5017 if (lhs == rhs)
5018 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005019
Eli Friedmana95d7572009-08-19 07:44:53 +00005020 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5021 // The caller can deal with this (e.g. pointer + int).
5022 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5023 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005024
5025 // At this point, we have two different arithmetic types.
5026
Eli Friedmana95d7572009-08-19 07:44:53 +00005027 // Handle complex types first (C99 6.3.1.8p1).
5028 if (lhs->isComplexType() || rhs->isComplexType()) {
5029 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005030 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005031 // convert the rhs to the lhs complex type.
5032 return lhs;
5033 }
Mike Stump1eb44332009-09-09 15:08:12 +00005034 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005035 // convert the lhs to the rhs complex type.
5036 return rhs;
5037 }
5038 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005039 // When both operands are complex, the shorter operand is converted to the
5040 // type of the longer, and that is the type of the result. This corresponds
5041 // to what is done when combining two real floating-point operands.
5042 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005043 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005044 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005045 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005046 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005047 // "double _Complex" is promoted to "long double _Complex".
5048 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005049
5050 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005051 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005052 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005053 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005054 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005055 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5056 // domains match. This is a requirement for our implementation, C99
5057 // does not require this promotion.
5058 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5059 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5060 return rhs;
5061 } else { // handle "_Complex double, double".
5062 return lhs;
5063 }
5064 }
5065 return lhs; // The domain/size match exactly.
5066 }
5067 // Now handle "real" floating types (i.e. float, double, long double).
5068 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5069 // if we have an integer operand, the result is the real floating type.
5070 if (rhs->isIntegerType()) {
5071 // convert rhs to the lhs floating point type.
5072 return lhs;
5073 }
5074 if (rhs->isComplexIntegerType()) {
5075 // convert rhs to the complex floating point type.
5076 return getComplexType(lhs);
5077 }
5078 if (lhs->isIntegerType()) {
5079 // convert lhs to the rhs floating point type.
5080 return rhs;
5081 }
Mike Stump1eb44332009-09-09 15:08:12 +00005082 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005083 // convert lhs to the complex floating point type.
5084 return getComplexType(rhs);
5085 }
5086 // We have two real floating types, float/complex combos were handled above.
5087 // Convert the smaller operand to the bigger result.
5088 int result = getFloatingTypeOrder(lhs, rhs);
5089 if (result > 0) // convert the rhs
5090 return lhs;
5091 assert(result < 0 && "illegal float comparison");
5092 return rhs; // convert the lhs
5093 }
5094 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5095 // Handle GCC complex int extension.
5096 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5097 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5098
5099 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005100 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005101 rhsComplexInt->getElementType()) >= 0)
5102 return lhs; // convert the rhs
5103 return rhs;
5104 } else if (lhsComplexInt && rhs->isIntegerType()) {
5105 // convert the rhs to the lhs complex type.
5106 return lhs;
5107 } else if (rhsComplexInt && lhs->isIntegerType()) {
5108 // convert the lhs to the rhs complex type.
5109 return rhs;
5110 }
5111 }
5112 // Finally, we have two differing integer types.
5113 // The rules for this case are in C99 6.3.1.8
5114 int compare = getIntegerTypeOrder(lhs, rhs);
5115 bool lhsSigned = lhs->isSignedIntegerType(),
5116 rhsSigned = rhs->isSignedIntegerType();
5117 QualType destType;
5118 if (lhsSigned == rhsSigned) {
5119 // Same signedness; use the higher-ranked type
5120 destType = compare >= 0 ? lhs : rhs;
5121 } else if (compare != (lhsSigned ? 1 : -1)) {
5122 // The unsigned type has greater than or equal rank to the
5123 // signed type, so use the unsigned type
5124 destType = lhsSigned ? rhs : lhs;
5125 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5126 // The two types are different widths; if we are here, that
5127 // means the signed type is larger than the unsigned type, so
5128 // use the signed type.
5129 destType = lhsSigned ? lhs : rhs;
5130 } else {
5131 // The signed type is higher-ranked than the unsigned type,
5132 // but isn't actually any bigger (like unsigned int and long
5133 // on most 32-bit systems). Use the unsigned type corresponding
5134 // to the signed type.
5135 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5136 }
5137 return destType;
5138}