blob: d8c1c84858249fc4ec4625b67f3190f6a5d52b84 [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,
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002243 unsigned NumProtocols,
2244 unsigned Quals) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002245 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002246 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002247 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002248
2249 void *InsertPos = 0;
2250 if (ObjCObjectPointerType *QT =
2251 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002252 return getQualifiedType(QualType(QT, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002253
John McCall54e14c42009-10-22 22:37:11 +00002254 // Sort the protocol list alphabetically to canonicalize it.
2255 QualType Canonical;
2256 if (!InterfaceT.isCanonical() ||
2257 !areSortedAndUniqued(Protocols, NumProtocols)) {
2258 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2259 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2260 unsigned UniqueCount = NumProtocols;
2261
2262 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2263 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2264
2265 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2266 &Sorted[0], UniqueCount);
2267 } else {
2268 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2269 Protocols, NumProtocols);
2270 }
2271
2272 // Regenerate InsertPos.
2273 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2274 }
2275
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002276 // No match.
2277 unsigned Size = sizeof(ObjCObjectPointerType)
2278 + NumProtocols * sizeof(ObjCProtocolDecl *);
2279 void *Mem = Allocate(Size, TypeAlignment);
2280 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2281 InterfaceT,
2282 Protocols,
2283 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002285 Types.push_back(QType);
2286 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002287 return getQualifiedType(QualType(QType, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002288}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002289
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002290/// getObjCInterfaceType - Return the unique reference to the type for the
2291/// specified ObjC interface decl. The list of protocols is optional.
2292QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002293 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002294 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002295 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002297 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002298 if (ObjCInterfaceType *QT =
2299 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002300 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002301
John McCall54e14c42009-10-22 22:37:11 +00002302 // Sort the protocol list alphabetically to canonicalize it.
2303 QualType Canonical;
2304 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2305 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2306 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2307
2308 unsigned UniqueCount = NumProtocols;
2309 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2310
2311 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2312
2313 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2314 }
2315
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002316 unsigned Size = sizeof(ObjCInterfaceType)
2317 + NumProtocols * sizeof(ObjCProtocolDecl *);
2318 void *Mem = Allocate(Size, TypeAlignment);
2319 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2320 const_cast<ObjCInterfaceDecl*>(Decl),
2321 Protocols,
2322 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002323
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002324 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002325 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002326 return QualType(QType, 0);
2327}
2328
Douglas Gregor72564e72009-02-26 23:50:07 +00002329/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2330/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002331/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002332/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002333/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002334QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002335 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002336 if (tofExpr->isTypeDependent()) {
2337 llvm::FoldingSetNodeID ID;
2338 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Douglas Gregorb1975722009-07-30 23:18:24 +00002340 void *InsertPos = 0;
2341 DependentTypeOfExprType *Canon
2342 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2343 if (Canon) {
2344 // We already have a "canonical" version of an identical, dependent
2345 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002346 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002347 QualType((TypeOfExprType*)Canon, 0));
2348 }
2349 else {
2350 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002351 Canon
2352 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002353 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2354 toe = Canon;
2355 }
2356 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002357 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002358 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002359 }
Steve Naroff9752f252007-08-01 18:02:17 +00002360 Types.push_back(toe);
2361 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002362}
2363
Steve Naroff9752f252007-08-01 18:02:17 +00002364/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2365/// TypeOfType AST's. The only motivation to unique these nodes would be
2366/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002367/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002368/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002369QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002370 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002371 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002372 Types.push_back(tot);
2373 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002374}
2375
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002376/// getDecltypeForExpr - Given an expr, will return the decltype for that
2377/// expression, according to the rules in C++0x [dcl.type.simple]p4
2378static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002379 if (e->isTypeDependent())
2380 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002382 // If e is an id expression or a class member access, decltype(e) is defined
2383 // as the type of the entity named by e.
2384 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2385 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2386 return VD->getType();
2387 }
2388 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2389 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2390 return FD->getType();
2391 }
2392 // If e is a function call or an invocation of an overloaded operator,
2393 // (parentheses around e are ignored), decltype(e) is defined as the
2394 // return type of that function.
2395 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2396 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002398 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002399
2400 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002401 // defined as T&, otherwise decltype(e) is defined as T.
2402 if (e->isLvalue(Context) == Expr::LV_Valid)
2403 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002405 return T;
2406}
2407
Anders Carlsson395b4752009-06-24 19:06:50 +00002408/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2409/// DecltypeType AST's. The only motivation to unique these nodes would be
2410/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002411/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002412/// on canonical type's (which are always unique).
2413QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002414 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002415 if (e->isTypeDependent()) {
2416 llvm::FoldingSetNodeID ID;
2417 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002419 void *InsertPos = 0;
2420 DependentDecltypeType *Canon
2421 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2422 if (Canon) {
2423 // We already have a "canonical" version of an equivalent, dependent
2424 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002425 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002426 QualType((DecltypeType*)Canon, 0));
2427 }
2428 else {
2429 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002430 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002431 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2432 dt = Canon;
2433 }
2434 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002435 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002436 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002437 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002438 Types.push_back(dt);
2439 return QualType(dt, 0);
2440}
2441
Reid Spencer5f016e22007-07-11 17:01:13 +00002442/// getTagDeclType - Return the unique reference to the type for the
2443/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002444QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002445 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002446 // FIXME: What is the design on getTagDeclType when it requires casting
2447 // away const? mutable?
2448 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002449}
2450
Mike Stump1eb44332009-09-09 15:08:12 +00002451/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2452/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2453/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002454CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002455 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002456}
2457
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002458/// getSignedWCharType - Return the type of "signed wchar_t".
2459/// Used when in C++, as a GCC extension.
2460QualType ASTContext::getSignedWCharType() const {
2461 // FIXME: derive from "Target" ?
2462 return WCharTy;
2463}
2464
2465/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2466/// Used when in C++, as a GCC extension.
2467QualType ASTContext::getUnsignedWCharType() const {
2468 // FIXME: derive from "Target" ?
2469 return UnsignedIntTy;
2470}
2471
Chris Lattner8b9023b2007-07-13 03:05:23 +00002472/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2473/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2474QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002475 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002476}
2477
Chris Lattnere6327742008-04-02 05:18:44 +00002478//===----------------------------------------------------------------------===//
2479// Type Operators
2480//===----------------------------------------------------------------------===//
2481
John McCall54e14c42009-10-22 22:37:11 +00002482CanQualType ASTContext::getCanonicalParamType(QualType T) {
2483 // Push qualifiers into arrays, and then discard any remaining
2484 // qualifiers.
2485 T = getCanonicalType(T);
2486 const Type *Ty = T.getTypePtr();
2487
2488 QualType Result;
2489 if (isa<ArrayType>(Ty)) {
2490 Result = getArrayDecayedType(QualType(Ty,0));
2491 } else if (isa<FunctionType>(Ty)) {
2492 Result = getPointerType(QualType(Ty, 0));
2493 } else {
2494 Result = QualType(Ty, 0);
2495 }
2496
2497 return CanQualType::CreateUnsafe(Result);
2498}
2499
Chris Lattner77c96472008-04-06 22:41:35 +00002500/// getCanonicalType - Return the canonical (structural) type corresponding to
2501/// the specified potentially non-canonical type. The non-canonical version
2502/// of a type may have many "decorated" versions of types. Decorators can
2503/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2504/// to be free of any of these, allowing two canonical types to be compared
2505/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002506CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002507 QualifierCollector Quals;
2508 const Type *Ptr = Quals.strip(T);
2509 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002510
John McCall0953e762009-09-24 19:53:00 +00002511 // The canonical internal type will be the canonical type *except*
2512 // that we push type qualifiers down through array types.
2513
2514 // If there are no new qualifiers to push down, stop here.
2515 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002516 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002517
John McCall0953e762009-09-24 19:53:00 +00002518 // If the type qualifiers are on an array type, get the canonical
2519 // type of the array with the qualifiers applied to the element
2520 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2522 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002523 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002525 // Get the canonical version of the element with the extra qualifiers on it.
2526 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002527 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002528 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002530 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002531 return CanQualType::CreateUnsafe(
2532 getConstantArrayType(NewEltTy, CAT->getSize(),
2533 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002534 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002535 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002536 return CanQualType::CreateUnsafe(
2537 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002538 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002539
Douglas Gregor898574e2008-12-05 23:32:09 +00002540 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002541 return CanQualType::CreateUnsafe(
2542 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002543 DSAT->getSizeExpr() ?
2544 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002545 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002546 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002547 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002548
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002549 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002550 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002551 VAT->getSizeExpr() ?
2552 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002553 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002554 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002555 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002556}
2557
Chandler Carruth28e318c2009-12-29 07:16:59 +00002558QualType ASTContext::getUnqualifiedArrayType(QualType T,
2559 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002560 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002561 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002562 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002563 }
2564
Chandler Carruth28e318c2009-12-29 07:16:59 +00002565 const ArrayType *AT = cast<ArrayType>(T);
2566 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002567 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002568 if (Elt == UnqualElt)
2569 return T;
2570
2571 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2572 return getConstantArrayType(UnqualElt, CAT->getSize(),
2573 CAT->getSizeModifier(), 0);
2574 }
2575
2576 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2577 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2578 }
2579
2580 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2581 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2582 DSAT->getSizeModifier(), 0,
2583 SourceRange());
2584}
2585
John McCall80ad16f2009-11-24 18:42:40 +00002586DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2587 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2588 return TD->getDeclName();
2589
2590 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2591 if (DTN->isIdentifier()) {
2592 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2593 } else {
2594 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2595 }
2596 }
2597
John McCall0bd6feb2009-12-02 08:04:21 +00002598 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2599 assert(Storage);
2600 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002601}
2602
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002603TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2604 // If this template name refers to a template, the canonical
2605 // template name merely stores the template itself.
2606 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002607 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002608
John McCall0bd6feb2009-12-02 08:04:21 +00002609 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002611 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2612 assert(DTN && "Non-dependent template names must refer to template decls.");
2613 return DTN->CanonicalTemplateName;
2614}
2615
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002616bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2617 X = getCanonicalTemplateName(X);
2618 Y = getCanonicalTemplateName(Y);
2619 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2620}
2621
Mike Stump1eb44332009-09-09 15:08:12 +00002622TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002623ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2624 switch (Arg.getKind()) {
2625 case TemplateArgument::Null:
2626 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Douglas Gregor1275ae02009-07-28 23:00:59 +00002628 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002629 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002630
Douglas Gregor1275ae02009-07-28 23:00:59 +00002631 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002632 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Douglas Gregor788cd062009-11-11 01:00:40 +00002634 case TemplateArgument::Template:
2635 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2636
Douglas Gregor1275ae02009-07-28 23:00:59 +00002637 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002638 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002639 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Douglas Gregor1275ae02009-07-28 23:00:59 +00002641 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002642 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Douglas Gregor1275ae02009-07-28 23:00:59 +00002644 case TemplateArgument::Pack: {
2645 // FIXME: Allocate in ASTContext
2646 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2647 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002648 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002649 AEnd = Arg.pack_end();
2650 A != AEnd; (void)++A, ++Idx)
2651 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Douglas Gregor1275ae02009-07-28 23:00:59 +00002653 TemplateArgument Result;
2654 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2655 return Result;
2656 }
2657 }
2658
2659 // Silence GCC warning
2660 assert(false && "Unhandled template argument kind");
2661 return TemplateArgument();
2662}
2663
Douglas Gregord57959a2009-03-27 23:10:48 +00002664NestedNameSpecifier *
2665ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002666 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002667 return 0;
2668
2669 switch (NNS->getKind()) {
2670 case NestedNameSpecifier::Identifier:
2671 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002672 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002673 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2674 NNS->getAsIdentifier());
2675
2676 case NestedNameSpecifier::Namespace:
2677 // A namespace is canonical; build a nested-name-specifier with
2678 // this namespace and no prefix.
2679 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2680
2681 case NestedNameSpecifier::TypeSpec:
2682 case NestedNameSpecifier::TypeSpecWithTemplate: {
2683 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002684 return NestedNameSpecifier::Create(*this, 0,
2685 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002686 T.getTypePtr());
2687 }
2688
2689 case NestedNameSpecifier::Global:
2690 // The global specifier is canonical and unique.
2691 return NNS;
2692 }
2693
2694 // Required to silence a GCC warning
2695 return 0;
2696}
2697
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002698
2699const ArrayType *ASTContext::getAsArrayType(QualType T) {
2700 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002701 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002702 // Handle the common positive case fast.
2703 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2704 return AT;
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
John McCall0953e762009-09-24 19:53:00 +00002707 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002708 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002709 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002710 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002711
John McCall0953e762009-09-24 19:53:00 +00002712 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002713 // implements C99 6.7.3p8: "If the specification of an array type includes
2714 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002716 // If we get here, we either have type qualifiers on the type, or we have
2717 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002718 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002719
John McCall0953e762009-09-24 19:53:00 +00002720 QualifierCollector Qs;
2721 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002723 // If we have a simple case, just return now.
2724 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002725 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002726 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002728 // Otherwise, we have an array and we have qualifiers on it. Push the
2729 // qualifiers into the array element type and return a new array type.
2730 // Get the canonical version of the element with the extra qualifiers on it.
2731 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002732 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002734 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2735 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2736 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002737 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002738 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2739 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2740 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002741 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002742
Mike Stump1eb44332009-09-09 15:08:12 +00002743 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002744 = dyn_cast<DependentSizedArrayType>(ATy))
2745 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002746 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002747 DSAT->getSizeExpr() ?
2748 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002749 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002750 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002751 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002753 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002754 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002755 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002756 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002757 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002758 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002759 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002760}
2761
2762
Chris Lattnere6327742008-04-02 05:18:44 +00002763/// getArrayDecayedType - Return the properly qualified result of decaying the
2764/// specified array type to a pointer. This operation is non-trivial when
2765/// handling typedefs etc. The canonical type of "T" must be an array type,
2766/// this returns a pointer to a properly qualified element of the array.
2767///
2768/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2769QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002770 // Get the element type with 'getAsArrayType' so that we don't lose any
2771 // typedefs in the element type of the array. This also handles propagation
2772 // of type qualifiers from the array type into the element type if present
2773 // (C99 6.7.3p8).
2774 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2775 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002777 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002778
2779 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002780 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002781}
2782
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002783QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002784 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002785 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002786 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002787 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2788 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002789 } else {
John McCall0953e762009-09-24 19:53:00 +00002790 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002791 }
2792 }
2793}
2794
Anders Carlssonfbbce492009-09-25 01:23:32 +00002795QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2796 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Anders Carlssonfbbce492009-09-25 01:23:32 +00002798 if (const ArrayType *AT = getAsArrayType(ElemTy))
2799 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Anders Carlsson6183a992008-12-21 03:44:36 +00002801 return ElemTy;
2802}
2803
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002804/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002805uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002806ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2807 uint64_t ElementCount = 1;
2808 do {
2809 ElementCount *= CA->getSize().getZExtValue();
2810 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2811 } while (CA);
2812 return ElementCount;
2813}
2814
Reid Spencer5f016e22007-07-11 17:01:13 +00002815/// getFloatingRank - Return a relative rank for floating point types.
2816/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002817static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002818 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002820
John McCall183700f2009-09-21 23:43:11 +00002821 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2822 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002823 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 case BuiltinType::Float: return FloatRank;
2825 case BuiltinType::Double: return DoubleRank;
2826 case BuiltinType::LongDouble: return LongDoubleRank;
2827 }
2828}
2829
Mike Stump1eb44332009-09-09 15:08:12 +00002830/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2831/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002832/// 'typeDomain' is a real floating point or complex type.
2833/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002834QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2835 QualType Domain) const {
2836 FloatingRank EltRank = getFloatingRank(Size);
2837 if (Domain->isComplexType()) {
2838 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002839 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002840 case FloatRank: return FloatComplexTy;
2841 case DoubleRank: return DoubleComplexTy;
2842 case LongDoubleRank: return LongDoubleComplexTy;
2843 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 }
Chris Lattner1361b112008-04-06 23:58:54 +00002845
2846 assert(Domain->isRealFloatingType() && "Unknown domain!");
2847 switch (EltRank) {
2848 default: assert(0 && "getFloatingRank(): illegal value for rank");
2849 case FloatRank: return FloatTy;
2850 case DoubleRank: return DoubleTy;
2851 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002852 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002853}
2854
Chris Lattner7cfeb082008-04-06 23:55:33 +00002855/// getFloatingTypeOrder - Compare the rank of the two specified floating
2856/// point types, ignoring the domain of the type (i.e. 'double' ==
2857/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002858/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002859int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2860 FloatingRank LHSR = getFloatingRank(LHS);
2861 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Chris Lattnera75cea32008-04-06 23:38:49 +00002863 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002864 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002865 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002866 return 1;
2867 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002868}
2869
Chris Lattnerf52ab252008-04-06 22:59:24 +00002870/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2871/// routine will assert if passed a built-in type that isn't an integer or enum,
2872/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002873unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002874 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002875 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002876 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002877
Eli Friedmana3426752009-07-05 23:44:27 +00002878 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2879 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2880
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002881 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2882 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2883
2884 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2885 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2886
Chris Lattnerf52ab252008-04-06 22:59:24 +00002887 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002888 default: assert(0 && "getIntegerRank(): not a built-in integer");
2889 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002890 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002891 case BuiltinType::Char_S:
2892 case BuiltinType::Char_U:
2893 case BuiltinType::SChar:
2894 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002895 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002896 case BuiltinType::Short:
2897 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002898 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002899 case BuiltinType::Int:
2900 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002901 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002902 case BuiltinType::Long:
2903 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002904 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002905 case BuiltinType::LongLong:
2906 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002907 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002908 case BuiltinType::Int128:
2909 case BuiltinType::UInt128:
2910 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002911 }
2912}
2913
Eli Friedman04e83572009-08-20 04:21:42 +00002914/// \brief Whether this is a promotable bitfield reference according
2915/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2916///
2917/// \returns the type this bit-field will promote to, or NULL if no
2918/// promotion occurs.
2919QualType ASTContext::isPromotableBitField(Expr *E) {
2920 FieldDecl *Field = E->getBitField();
2921 if (!Field)
2922 return QualType();
2923
2924 QualType FT = Field->getType();
2925
2926 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2927 uint64_t BitWidth = BitWidthAP.getZExtValue();
2928 uint64_t IntSize = getTypeSize(IntTy);
2929 // GCC extension compatibility: if the bit-field size is less than or equal
2930 // to the size of int, it gets promoted no matter what its type is.
2931 // For instance, unsigned long bf : 4 gets promoted to signed int.
2932 if (BitWidth < IntSize)
2933 return IntTy;
2934
2935 if (BitWidth == IntSize)
2936 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2937
2938 // Types bigger than int are not subject to promotions, and therefore act
2939 // like the base type.
2940 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2941 // is ridiculous.
2942 return QualType();
2943}
2944
Eli Friedmana95d7572009-08-19 07:44:53 +00002945/// getPromotedIntegerType - Returns the type that Promotable will
2946/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2947/// integer type.
2948QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2949 assert(!Promotable.isNull());
2950 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002951 if (const EnumType *ET = Promotable->getAs<EnumType>())
2952 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002953 if (Promotable->isSignedIntegerType())
2954 return IntTy;
2955 uint64_t PromotableSize = getTypeSize(Promotable);
2956 uint64_t IntSize = getTypeSize(IntTy);
2957 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2958 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2959}
2960
Mike Stump1eb44332009-09-09 15:08:12 +00002961/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002962/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002963/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002964int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002965 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2966 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002967 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Chris Lattnerf52ab252008-04-06 22:59:24 +00002969 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2970 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002971
Chris Lattner7cfeb082008-04-06 23:55:33 +00002972 unsigned LHSRank = getIntegerRank(LHSC);
2973 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Chris Lattner7cfeb082008-04-06 23:55:33 +00002975 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2976 if (LHSRank == RHSRank) return 0;
2977 return LHSRank > RHSRank ? 1 : -1;
2978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Chris Lattner7cfeb082008-04-06 23:55:33 +00002980 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2981 if (LHSUnsigned) {
2982 // If the unsigned [LHS] type is larger, return it.
2983 if (LHSRank >= RHSRank)
2984 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Chris Lattner7cfeb082008-04-06 23:55:33 +00002986 // If the signed type can represent all values of the unsigned type, it
2987 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002988 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002989 return -1;
2990 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002991
Chris Lattner7cfeb082008-04-06 23:55:33 +00002992 // If the unsigned [RHS] type is larger, return it.
2993 if (RHSRank >= LHSRank)
2994 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Chris Lattner7cfeb082008-04-06 23:55:33 +00002996 // If the signed type can represent all values of the unsigned type, it
2997 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002998 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002999 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003000}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003001
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003002static RecordDecl *
3003CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3004 SourceLocation L, IdentifierInfo *Id) {
3005 if (Ctx.getLangOptions().CPlusPlus)
3006 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3007 else
3008 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3009}
3010
Mike Stump1eb44332009-09-09 15:08:12 +00003011// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003012QualType ASTContext::getCFConstantStringType() {
3013 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003014 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003015 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3016 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003017 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003018
Anders Carlssonf06273f2007-11-19 00:25:30 +00003019 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Anders Carlsson71993dd2007-08-17 05:31:46 +00003021 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003022 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003023 // int flags;
3024 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003025 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003026 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003027 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003028 FieldTypes[3] = LongTy;
3029
Anders Carlsson71993dd2007-08-17 05:31:46 +00003030 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003031 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003032 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003033 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003034 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003035 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003036 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003037 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003038 }
3039
Douglas Gregor838db382010-02-11 01:19:42 +00003040 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003041 }
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Anders Carlsson71993dd2007-08-17 05:31:46 +00003043 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003044}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003045
Douglas Gregor319ac892009-04-23 22:29:11 +00003046void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003047 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003048 assert(Rec && "Invalid CFConstantStringType");
3049 CFConstantStringTypeDecl = Rec->getDecl();
3050}
3051
Mike Stump1eb44332009-09-09 15:08:12 +00003052QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003053 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003054 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003055 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3056 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003057 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003059 QualType FieldTypes[] = {
3060 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003061 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003062 getPointerType(UnsignedLongTy),
3063 getConstantArrayType(UnsignedLongTy,
3064 llvm::APInt(32, 5), ArrayType::Normal, 0)
3065 };
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Douglas Gregor44b43212008-12-11 16:49:14 +00003067 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003068 FieldDecl *Field = FieldDecl::Create(*this,
3069 ObjCFastEnumerationStateTypeDecl,
3070 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003071 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003072 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003073 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003074 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Douglas Gregor838db382010-02-11 01:19:42 +00003077 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003078 }
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003080 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3081}
3082
Mike Stumpadaaad32009-10-20 02:12:22 +00003083QualType ASTContext::getBlockDescriptorType() {
3084 if (BlockDescriptorType)
3085 return getTagDeclType(BlockDescriptorType);
3086
3087 RecordDecl *T;
3088 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003089 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3090 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003091 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003092
3093 QualType FieldTypes[] = {
3094 UnsignedLongTy,
3095 UnsignedLongTy,
3096 };
3097
3098 const char *FieldNames[] = {
3099 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003100 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003101 };
3102
3103 for (size_t i = 0; i < 2; ++i) {
3104 FieldDecl *Field = FieldDecl::Create(*this,
3105 T,
3106 SourceLocation(),
3107 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003108 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003109 /*BitWidth=*/0,
3110 /*Mutable=*/false);
3111 T->addDecl(Field);
3112 }
3113
Douglas Gregor838db382010-02-11 01:19:42 +00003114 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003115
3116 BlockDescriptorType = T;
3117
3118 return getTagDeclType(BlockDescriptorType);
3119}
3120
3121void ASTContext::setBlockDescriptorType(QualType T) {
3122 const RecordType *Rec = T->getAs<RecordType>();
3123 assert(Rec && "Invalid BlockDescriptorType");
3124 BlockDescriptorType = Rec->getDecl();
3125}
3126
Mike Stump083c25e2009-10-22 00:49:09 +00003127QualType ASTContext::getBlockDescriptorExtendedType() {
3128 if (BlockDescriptorExtendedType)
3129 return getTagDeclType(BlockDescriptorExtendedType);
3130
3131 RecordDecl *T;
3132 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003133 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3134 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003135 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003136
3137 QualType FieldTypes[] = {
3138 UnsignedLongTy,
3139 UnsignedLongTy,
3140 getPointerType(VoidPtrTy),
3141 getPointerType(VoidPtrTy)
3142 };
3143
3144 const char *FieldNames[] = {
3145 "reserved",
3146 "Size",
3147 "CopyFuncPtr",
3148 "DestroyFuncPtr"
3149 };
3150
3151 for (size_t i = 0; i < 4; ++i) {
3152 FieldDecl *Field = FieldDecl::Create(*this,
3153 T,
3154 SourceLocation(),
3155 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003156 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003157 /*BitWidth=*/0,
3158 /*Mutable=*/false);
3159 T->addDecl(Field);
3160 }
3161
Douglas Gregor838db382010-02-11 01:19:42 +00003162 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003163
3164 BlockDescriptorExtendedType = T;
3165
3166 return getTagDeclType(BlockDescriptorExtendedType);
3167}
3168
3169void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3170 const RecordType *Rec = T->getAs<RecordType>();
3171 assert(Rec && "Invalid BlockDescriptorType");
3172 BlockDescriptorExtendedType = Rec->getDecl();
3173}
3174
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003175bool ASTContext::BlockRequiresCopying(QualType Ty) {
3176 if (Ty->isBlockPointerType())
3177 return true;
3178 if (isObjCNSObjectType(Ty))
3179 return true;
3180 if (Ty->isObjCObjectPointerType())
3181 return true;
3182 return false;
3183}
3184
3185QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3186 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003187 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003188 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003189 // unsigned int __flags;
3190 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003191 // void *__copy_helper; // as needed
3192 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003193 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003194 // } *
3195
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003196 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3197
3198 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003199 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003200 llvm::SmallString<36> Name;
3201 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3202 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003203 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003204 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3205 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003206 T->startDefinition();
3207 QualType Int32Ty = IntTy;
3208 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3209 QualType FieldTypes[] = {
3210 getPointerType(VoidPtrTy),
3211 getPointerType(getTagDeclType(T)),
3212 Int32Ty,
3213 Int32Ty,
3214 getPointerType(VoidPtrTy),
3215 getPointerType(VoidPtrTy),
3216 Ty
3217 };
3218
3219 const char *FieldNames[] = {
3220 "__isa",
3221 "__forwarding",
3222 "__flags",
3223 "__size",
3224 "__copy_helper",
3225 "__destroy_helper",
3226 DeclName,
3227 };
3228
3229 for (size_t i = 0; i < 7; ++i) {
3230 if (!HasCopyAndDispose && i >=4 && i <= 5)
3231 continue;
3232 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3233 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003234 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003235 /*BitWidth=*/0, /*Mutable=*/false);
3236 T->addDecl(Field);
3237 }
3238
Douglas Gregor838db382010-02-11 01:19:42 +00003239 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003240
3241 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003242}
3243
3244
3245QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003246 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003247 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003248 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003249 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003250 llvm::SmallString<36> Name;
3251 llvm::raw_svector_ostream(Name) << "__block_literal_"
3252 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003253 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003254 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3255 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003256 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003257 QualType FieldTypes[] = {
3258 getPointerType(VoidPtrTy),
3259 IntTy,
3260 IntTy,
3261 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003262 (BlockHasCopyDispose ?
3263 getPointerType(getBlockDescriptorExtendedType()) :
3264 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003265 };
3266
3267 const char *FieldNames[] = {
3268 "__isa",
3269 "__flags",
3270 "__reserved",
3271 "__FuncPtr",
3272 "__descriptor"
3273 };
3274
3275 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003276 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003277 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003278 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003279 /*BitWidth=*/0, /*Mutable=*/false);
3280 T->addDecl(Field);
3281 }
3282
3283 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3284 const Expr *E = BlockDeclRefDecls[i];
3285 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3286 clang::IdentifierInfo *Name = 0;
3287 if (BDRE) {
3288 const ValueDecl *D = BDRE->getDecl();
3289 Name = &Idents.get(D->getName());
3290 }
3291 QualType FieldType = E->getType();
3292
3293 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003294 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3295 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003296
3297 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003298 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003299 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003300 T->addDecl(Field);
3301 }
3302
Douglas Gregor838db382010-02-11 01:19:42 +00003303 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003304
3305 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003306}
3307
Douglas Gregor319ac892009-04-23 22:29:11 +00003308void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003309 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003310 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3311 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3312}
3313
Anders Carlssone8c49532007-10-29 06:33:42 +00003314// This returns true if a type has been typedefed to BOOL:
3315// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003316static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003317 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003318 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3319 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003321 return false;
3322}
3323
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003324/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003325/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003326CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003327 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003329 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003330 if (sz.isPositive() && type->isIntegralType())
3331 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003332 // Treat arrays as pointers, since that's how they're passed in.
3333 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003334 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003335 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003336}
3337
3338static inline
3339std::string charUnitsToString(const CharUnits &CU) {
3340 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003341}
3342
David Chisnall5e530af2009-11-17 19:33:30 +00003343/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3344/// declaration.
3345void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3346 std::string& S) {
3347 const BlockDecl *Decl = Expr->getBlockDecl();
3348 QualType BlockTy =
3349 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3350 // Encode result type.
3351 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3352 // Compute size of all parameters.
3353 // Start with computing size of a pointer in number of bytes.
3354 // FIXME: There might(should) be a better way of doing this computation!
3355 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003356 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3357 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003358 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3359 E = Decl->param_end(); PI != E; ++PI) {
3360 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003361 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003362 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003363 ParmOffset += sz;
3364 }
3365 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003366 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003367 // Block pointer and offset.
3368 S += "@?0";
3369 ParmOffset = PtrSize;
3370
3371 // Argument types.
3372 ParmOffset = PtrSize;
3373 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3374 Decl->param_end(); PI != E; ++PI) {
3375 ParmVarDecl *PVDecl = *PI;
3376 QualType PType = PVDecl->getOriginalType();
3377 if (const ArrayType *AT =
3378 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3379 // Use array's original type only if it has known number of
3380 // elements.
3381 if (!isa<ConstantArrayType>(AT))
3382 PType = PVDecl->getType();
3383 } else if (PType->isFunctionType())
3384 PType = PVDecl->getType();
3385 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003386 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003387 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003388 }
3389}
3390
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003391/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003392/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003393void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003394 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003395 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003396 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003397 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003398 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003399 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003400 // Compute size of all parameters.
3401 // Start with computing size of a pointer in number of bytes.
3402 // FIXME: There might(should) be a better way of doing this computation!
3403 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003404 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003405 // The first two arguments (self and _cmd) are pointers; account for
3406 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003407 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003408 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3409 E = Decl->param_end(); PI != E; ++PI) {
3410 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003411 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003412 assert (sz.isPositive() &&
3413 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003414 ParmOffset += sz;
3415 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003416 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003417 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003418 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003420 // Argument types.
3421 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003422 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3423 E = Decl->param_end(); PI != E; ++PI) {
3424 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003425 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003426 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003427 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3428 // Use array's original type only if it has known number of
3429 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003430 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003431 PType = PVDecl->getType();
3432 } else if (PType->isFunctionType())
3433 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003434 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003435 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003436 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003437 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003438 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003439 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003440 }
3441}
3442
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003443/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003444/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003445/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3446/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003447/// Property attributes are stored as a comma-delimited C string. The simple
3448/// attributes readonly and bycopy are encoded as single characters. The
3449/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3450/// encoded as single characters, followed by an identifier. Property types
3451/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003452/// these attributes are defined by the following enumeration:
3453/// @code
3454/// enum PropertyAttributes {
3455/// kPropertyReadOnly = 'R', // property is read-only.
3456/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3457/// kPropertyByref = '&', // property is a reference to the value last assigned
3458/// kPropertyDynamic = 'D', // property is dynamic
3459/// kPropertyGetter = 'G', // followed by getter selector name
3460/// kPropertySetter = 'S', // followed by setter selector name
3461/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3462/// kPropertyType = 't' // followed by old-style type encoding.
3463/// kPropertyWeak = 'W' // 'weak' property
3464/// kPropertyStrong = 'P' // property GC'able
3465/// kPropertyNonAtomic = 'N' // property non-atomic
3466/// };
3467/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003468void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003469 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003470 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003471 // Collect information from the property implementation decl(s).
3472 bool Dynamic = false;
3473 ObjCPropertyImplDecl *SynthesizePID = 0;
3474
3475 // FIXME: Duplicated code due to poor abstraction.
3476 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003477 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003478 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3479 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003480 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003481 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003482 ObjCPropertyImplDecl *PID = *i;
3483 if (PID->getPropertyDecl() == PD) {
3484 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3485 Dynamic = true;
3486 } else {
3487 SynthesizePID = PID;
3488 }
3489 }
3490 }
3491 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003492 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003493 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003494 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003495 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003496 ObjCPropertyImplDecl *PID = *i;
3497 if (PID->getPropertyDecl() == PD) {
3498 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3499 Dynamic = true;
3500 } else {
3501 SynthesizePID = PID;
3502 }
3503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003505 }
3506 }
3507
3508 // FIXME: This is not very efficient.
3509 S = "T";
3510
3511 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003512 // GCC has some special rules regarding encoding of properties which
3513 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003514 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003515 true /* outermost type */,
3516 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003517
3518 if (PD->isReadOnly()) {
3519 S += ",R";
3520 } else {
3521 switch (PD->getSetterKind()) {
3522 case ObjCPropertyDecl::Assign: break;
3523 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003524 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003525 }
3526 }
3527
3528 // It really isn't clear at all what this means, since properties
3529 // are "dynamic by default".
3530 if (Dynamic)
3531 S += ",D";
3532
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003533 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3534 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003536 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3537 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003538 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003539 }
3540
3541 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3542 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003543 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003544 }
3545
3546 if (SynthesizePID) {
3547 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3548 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003549 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003550 }
3551
3552 // FIXME: OBJCGC: weak & strong
3553}
3554
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003555/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003556/// Another legacy compatibility encoding: 32-bit longs are encoded as
3557/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003558/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3559///
3560void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003561 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003562 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003563 if (BT->getKind() == BuiltinType::ULong &&
3564 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003565 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003566 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003567 if (BT->getKind() == BuiltinType::Long &&
3568 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003569 PointeeTy = IntTy;
3570 }
3571 }
3572}
3573
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003574void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003575 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003576 // We follow the behavior of gcc, expanding structures which are
3577 // directly pointed to, and expanding embedded structures. Note that
3578 // these rules are sufficient to prevent recursive encoding of the
3579 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003580 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003581 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003582}
3583
Mike Stump1eb44332009-09-09 15:08:12 +00003584static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003585 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003586 const Expr *E = FD->getBitWidth();
3587 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3588 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003589 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003590 S += 'b';
3591 S += llvm::utostr(N);
3592}
3593
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003594// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003595void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3596 bool ExpandPointedToStructures,
3597 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003598 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003599 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003600 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003601 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003602 if (FD && FD->isBitField())
3603 return EncodeBitField(this, S, FD);
3604 char encoding;
3605 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003606 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003607 case BuiltinType::Void: encoding = 'v'; break;
3608 case BuiltinType::Bool: encoding = 'B'; break;
3609 case BuiltinType::Char_U:
3610 case BuiltinType::UChar: encoding = 'C'; break;
3611 case BuiltinType::UShort: encoding = 'S'; break;
3612 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003613 case BuiltinType::ULong:
3614 encoding =
3615 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003616 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003617 case BuiltinType::UInt128: encoding = 'T'; break;
3618 case BuiltinType::ULongLong: encoding = 'Q'; break;
3619 case BuiltinType::Char_S:
3620 case BuiltinType::SChar: encoding = 'c'; break;
3621 case BuiltinType::Short: encoding = 's'; break;
3622 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003623 case BuiltinType::Long:
3624 encoding =
3625 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003626 break;
3627 case BuiltinType::LongLong: encoding = 'q'; break;
3628 case BuiltinType::Int128: encoding = 't'; break;
3629 case BuiltinType::Float: encoding = 'f'; break;
3630 case BuiltinType::Double: encoding = 'd'; break;
3631 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003632 }
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003634 S += encoding;
3635 return;
3636 }
Mike Stump1eb44332009-09-09 15:08:12 +00003637
John McCall183700f2009-09-21 23:43:11 +00003638 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003639 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003640 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003641 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003642 return;
3643 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003644
Ted Kremenek6217b802009-07-29 21:53:49 +00003645 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003646 if (PT->isObjCSelType()) {
3647 S += ':';
3648 return;
3649 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003650 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003651
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003652 bool isReadOnly = false;
3653 // For historical/compatibility reasons, the read-only qualifier of the
3654 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3655 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003656 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003657 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003658 if (OutermostType && T.isConstQualified()) {
3659 isReadOnly = true;
3660 S += 'r';
3661 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003662 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003663 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003664 while (P->getAs<PointerType>())
3665 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003666 if (P.isConstQualified()) {
3667 isReadOnly = true;
3668 S += 'r';
3669 }
3670 }
3671 if (isReadOnly) {
3672 // Another legacy compatibility encoding. Some ObjC qualifier and type
3673 // combinations need to be rearranged.
3674 // Rewrite "in const" from "nr" to "rn"
3675 const char * s = S.c_str();
3676 int len = S.length();
3677 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3678 std::string replace = "rn";
3679 S.replace(S.end()-2, S.end(), replace);
3680 }
3681 }
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003683 if (PointeeTy->isCharType()) {
3684 // char pointer types should be encoded as '*' unless it is a
3685 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003686 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003687 S += '*';
3688 return;
3689 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003690 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003691 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3692 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3693 S += '#';
3694 return;
3695 }
3696 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3697 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3698 S += '@';
3699 return;
3700 }
3701 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003702 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003703 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003704 getLegacyIntegralTypeEncoding(PointeeTy);
3705
Mike Stump1eb44332009-09-09 15:08:12 +00003706 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003707 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003708 return;
3709 }
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003711 if (const ArrayType *AT =
3712 // Ignore type qualifiers etc.
3713 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003714 if (isa<IncompleteArrayType>(AT)) {
3715 // Incomplete arrays are encoded as a pointer to the array element.
3716 S += '^';
3717
Mike Stump1eb44332009-09-09 15:08:12 +00003718 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003719 false, ExpandStructures, FD);
3720 } else {
3721 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Anders Carlsson559a8332009-02-22 01:38:57 +00003723 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3724 S += llvm::utostr(CAT->getSize().getZExtValue());
3725 else {
3726 //Variable length arrays are encoded as a regular array with 0 elements.
3727 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3728 S += '0';
3729 }
Mike Stump1eb44332009-09-09 15:08:12 +00003730
3731 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003732 false, ExpandStructures, FD);
3733 S += ']';
3734 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003735 return;
3736 }
Mike Stump1eb44332009-09-09 15:08:12 +00003737
John McCall183700f2009-09-21 23:43:11 +00003738 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003739 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003740 return;
3741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Ted Kremenek6217b802009-07-29 21:53:49 +00003743 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003744 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003745 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003746 // Anonymous structures print as '?'
3747 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3748 S += II->getName();
3749 } else {
3750 S += '?';
3751 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003752 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003753 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003754 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3755 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003756 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003757 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003758 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003759 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003760 S += '"';
3761 }
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003763 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003764 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003765 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003766 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003767 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003768 QualType qt = Field->getType();
3769 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003770 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003771 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003772 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003773 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003774 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003775 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003776 return;
3777 }
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003779 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003780 if (FD && FD->isBitField())
3781 EncodeBitField(this, S, FD);
3782 else
3783 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003784 return;
3785 }
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003787 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003788 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003789 return;
3790 }
Mike Stump1eb44332009-09-09 15:08:12 +00003791
John McCall0953e762009-09-24 19:53:00 +00003792 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003793 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003794 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003795 S += '{';
3796 const IdentifierInfo *II = OI->getIdentifier();
3797 S += II->getName();
3798 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003799 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003800 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003801 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003802 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003803 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003804 RecFields[i]);
3805 else
Mike Stump1eb44332009-09-09 15:08:12 +00003806 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003807 FD);
3808 }
3809 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003810 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003811 }
Mike Stump1eb44332009-09-09 15:08:12 +00003812
John McCall183700f2009-09-21 23:43:11 +00003813 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003814 if (OPT->isObjCIdType()) {
3815 S += '@';
3816 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003817 }
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Steve Naroff27d20a22009-10-28 22:03:49 +00003819 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3820 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3821 // Since this is a binary compatibility issue, need to consult with runtime
3822 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003823 S += '#';
3824 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003825 }
Mike Stump1eb44332009-09-09 15:08:12 +00003826
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003827 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003828 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003829 ExpandPointedToStructures,
3830 ExpandStructures, FD);
3831 if (FD || EncodingProperty) {
3832 // Note that we do extended encoding of protocol qualifer list
3833 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003834 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003835 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3836 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003837 S += '<';
3838 S += (*I)->getNameAsString();
3839 S += '>';
3840 }
3841 S += '"';
3842 }
3843 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003844 }
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003846 QualType PointeeTy = OPT->getPointeeType();
3847 if (!EncodingProperty &&
3848 isa<TypedefType>(PointeeTy.getTypePtr())) {
3849 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003850 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003851 // {...};
3852 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003853 getObjCEncodingForTypeImpl(PointeeTy, S,
3854 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003855 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003856 return;
3857 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003858
3859 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003860 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003861 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003862 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003863 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3864 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003865 S += '<';
3866 S += (*I)->getNameAsString();
3867 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003868 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003869 S += '"';
3870 }
3871 return;
3872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003874 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003875}
3876
Mike Stump1eb44332009-09-09 15:08:12 +00003877void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003878 std::string& S) const {
3879 if (QT & Decl::OBJC_TQ_In)
3880 S += 'n';
3881 if (QT & Decl::OBJC_TQ_Inout)
3882 S += 'N';
3883 if (QT & Decl::OBJC_TQ_Out)
3884 S += 'o';
3885 if (QT & Decl::OBJC_TQ_Bycopy)
3886 S += 'O';
3887 if (QT & Decl::OBJC_TQ_Byref)
3888 S += 'R';
3889 if (QT & Decl::OBJC_TQ_Oneway)
3890 S += 'V';
3891}
3892
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003893void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003894 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003896 BuiltinVaListType = T;
3897}
3898
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003900 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003901}
3902
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003903void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003904 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003905}
3906
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003907void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003908 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003909}
3910
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003911void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003912 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003913}
3914
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003915void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003916 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003917 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003919 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003920}
3921
John McCall0bd6feb2009-12-02 08:04:21 +00003922/// \brief Retrieve the template name that corresponds to a non-empty
3923/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003924TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3925 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003926 unsigned size = End - Begin;
3927 assert(size > 1 && "set is not overloaded!");
3928
3929 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3930 size * sizeof(FunctionTemplateDecl*));
3931 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3932
3933 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003934 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003935 NamedDecl *D = *I;
3936 assert(isa<FunctionTemplateDecl>(D) ||
3937 (isa<UsingShadowDecl>(D) &&
3938 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3939 *Storage++ = D;
3940 }
3941
3942 return TemplateName(OT);
3943}
3944
Douglas Gregor7532dc62009-03-30 22:58:21 +00003945/// \brief Retrieve the template name that represents a qualified
3946/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003947TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003948 bool TemplateKeyword,
3949 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003950 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003951 llvm::FoldingSetNodeID ID;
3952 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3953
3954 void *InsertPos = 0;
3955 QualifiedTemplateName *QTN =
3956 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3957 if (!QTN) {
3958 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3959 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3960 }
3961
3962 return TemplateName(QTN);
3963}
3964
3965/// \brief Retrieve the template name that represents a dependent
3966/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003967TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003968 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003969 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003970 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003971
3972 llvm::FoldingSetNodeID ID;
3973 DependentTemplateName::Profile(ID, NNS, Name);
3974
3975 void *InsertPos = 0;
3976 DependentTemplateName *QTN =
3977 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3978
3979 if (QTN)
3980 return TemplateName(QTN);
3981
3982 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3983 if (CanonNNS == NNS) {
3984 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3985 } else {
3986 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3987 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003988 DependentTemplateName *CheckQTN =
3989 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3990 assert(!CheckQTN && "Dependent type name canonicalization broken");
3991 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003992 }
3993
3994 DependentTemplateNames.InsertNode(QTN, InsertPos);
3995 return TemplateName(QTN);
3996}
3997
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003998/// \brief Retrieve the template name that represents a dependent
3999/// template name such as \c MetaFun::template operator+.
4000TemplateName
4001ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4002 OverloadedOperatorKind Operator) {
4003 assert((!NNS || NNS->isDependent()) &&
4004 "Nested name specifier must be dependent");
4005
4006 llvm::FoldingSetNodeID ID;
4007 DependentTemplateName::Profile(ID, NNS, Operator);
4008
4009 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004010 DependentTemplateName *QTN
4011 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004012
4013 if (QTN)
4014 return TemplateName(QTN);
4015
4016 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4017 if (CanonNNS == NNS) {
4018 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4019 } else {
4020 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4021 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004022
4023 DependentTemplateName *CheckQTN
4024 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4025 assert(!CheckQTN && "Dependent template name canonicalization broken");
4026 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004027 }
4028
4029 DependentTemplateNames.InsertNode(QTN, InsertPos);
4030 return TemplateName(QTN);
4031}
4032
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004033/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004034/// TargetInfo, produce the corresponding type. The unsigned @p Type
4035/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004036CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004037 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004038 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004039 case TargetInfo::SignedShort: return ShortTy;
4040 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4041 case TargetInfo::SignedInt: return IntTy;
4042 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4043 case TargetInfo::SignedLong: return LongTy;
4044 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4045 case TargetInfo::SignedLongLong: return LongLongTy;
4046 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4047 }
4048
4049 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004050 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004051}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004052
4053//===----------------------------------------------------------------------===//
4054// Type Predicates.
4055//===----------------------------------------------------------------------===//
4056
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004057/// isObjCNSObjectType - Return true if this is an NSObject object using
4058/// NSObject attribute on a c-style pointer type.
4059/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004060/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004061///
4062bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4063 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4064 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004065 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004066 return true;
4067 }
Mike Stump1eb44332009-09-09 15:08:12 +00004068 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004069}
4070
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004071/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4072/// garbage collection attribute.
4073///
John McCall0953e762009-09-24 19:53:00 +00004074Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4075 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004076 if (getLangOptions().ObjC1 &&
4077 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004078 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004079 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004080 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004081 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004082 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004083 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004084 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004085 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004086 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004087 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004088 // Non-pointers have none gc'able attribute regardless of the attribute
4089 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004090 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004091 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004092 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004093 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004094}
4095
Chris Lattner6ac46a42008-04-07 06:51:04 +00004096//===----------------------------------------------------------------------===//
4097// Type Compatibility Testing
4098//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004099
Mike Stump1eb44332009-09-09 15:08:12 +00004100/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004101/// compatible.
4102static bool areCompatVectorTypes(const VectorType *LHS,
4103 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004104 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004105 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004106 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004107}
4108
Steve Naroff4084c302009-07-23 01:01:38 +00004109//===----------------------------------------------------------------------===//
4110// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4111//===----------------------------------------------------------------------===//
4112
4113/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4114/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004115bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4116 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004117 if (lProto == rProto)
4118 return true;
4119 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4120 E = rProto->protocol_end(); PI != E; ++PI)
4121 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4122 return true;
4123 return false;
4124}
4125
Steve Naroff4084c302009-07-23 01:01:38 +00004126/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4127/// return true if lhs's protocols conform to rhs's protocol; false
4128/// otherwise.
4129bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4130 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4131 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4132 return false;
4133}
4134
4135/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4136/// ObjCQualifiedIDType.
4137bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4138 bool compare) {
4139 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004140 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004141 lhs->isObjCIdType() || lhs->isObjCClassType())
4142 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004143 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004144 rhs->isObjCIdType() || rhs->isObjCClassType())
4145 return true;
4146
4147 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004148 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Steve Naroff4084c302009-07-23 01:01:38 +00004150 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004151
Steve Naroff4084c302009-07-23 01:01:38 +00004152 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004153 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004154 // make sure we check the class hierarchy.
4155 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4156 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4157 E = lhsQID->qual_end(); I != E; ++I) {
4158 // when comparing an id<P> on lhs with a static type on rhs,
4159 // see if static class implements all of id's protocols, directly or
4160 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004161 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004162 return false;
4163 }
4164 }
4165 // If there are no qualifiers and no interface, we have an 'id'.
4166 return true;
4167 }
Mike Stump1eb44332009-09-09 15:08:12 +00004168 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004169 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4170 E = lhsQID->qual_end(); I != E; ++I) {
4171 ObjCProtocolDecl *lhsProto = *I;
4172 bool match = false;
4173
4174 // when comparing an id<P> on lhs with a static type on rhs,
4175 // see if static class implements all of id's protocols, directly or
4176 // through its super class and categories.
4177 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4178 E = rhsOPT->qual_end(); J != E; ++J) {
4179 ObjCProtocolDecl *rhsProto = *J;
4180 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4181 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4182 match = true;
4183 break;
4184 }
4185 }
Mike Stump1eb44332009-09-09 15:08:12 +00004186 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004187 // make sure we check the class hierarchy.
4188 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4189 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4190 E = lhsQID->qual_end(); I != E; ++I) {
4191 // when comparing an id<P> on lhs with a static type on rhs,
4192 // see if static class implements all of id's protocols, directly or
4193 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004194 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004195 match = true;
4196 break;
4197 }
4198 }
4199 }
4200 if (!match)
4201 return false;
4202 }
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Steve Naroff4084c302009-07-23 01:01:38 +00004204 return true;
4205 }
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Steve Naroff4084c302009-07-23 01:01:38 +00004207 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4208 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4209
Mike Stump1eb44332009-09-09 15:08:12 +00004210 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004211 lhs->getAsObjCInterfacePointerType()) {
4212 if (lhsOPT->qual_empty()) {
4213 bool match = false;
4214 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4215 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4216 E = rhsQID->qual_end(); I != E; ++I) {
4217 // when comparing an id<P> on lhs with a static type on rhs,
4218 // see if static class implements all of id's protocols, directly or
4219 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004220 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004221 match = true;
4222 break;
4223 }
4224 }
4225 if (!match)
4226 return false;
4227 }
4228 return true;
4229 }
Mike Stump1eb44332009-09-09 15:08:12 +00004230 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004231 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4232 E = lhsOPT->qual_end(); I != E; ++I) {
4233 ObjCProtocolDecl *lhsProto = *I;
4234 bool match = false;
4235
4236 // when comparing an id<P> on lhs with a static type on rhs,
4237 // see if static class implements all of id's protocols, directly or
4238 // through its super class and categories.
4239 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4240 E = rhsQID->qual_end(); J != E; ++J) {
4241 ObjCProtocolDecl *rhsProto = *J;
4242 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4243 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4244 match = true;
4245 break;
4246 }
4247 }
4248 if (!match)
4249 return false;
4250 }
4251 return true;
4252 }
4253 return false;
4254}
4255
Eli Friedman3d815e72008-08-22 00:56:42 +00004256/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004257/// compatible for assignment from RHS to LHS. This handles validation of any
4258/// protocol qualifiers on the LHS or RHS.
4259///
Steve Naroff14108da2009-07-10 23:34:53 +00004260bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4261 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004262 // If either type represents the built-in 'id' or 'Class' types, return true.
4263 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004264 return true;
4265
Steve Naroff4084c302009-07-23 01:01:38 +00004266 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004267 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4268 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004269 false);
4270
Steve Naroff14108da2009-07-10 23:34:53 +00004271 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4272 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004273 if (LHS && RHS) // We have 2 user-defined types.
4274 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Steve Naroff4084c302009-07-23 01:01:38 +00004276 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004277}
4278
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004279/// getIntersectionOfProtocols - This routine finds the intersection of set
4280/// of protocols inherited from two distinct objective-c pointer objects.
4281/// It is used to build composite qualifier list of the composite type of
4282/// the conditional expression involving two objective-c pointer objects.
4283static
4284void getIntersectionOfProtocols(ASTContext &Context,
4285 const ObjCObjectPointerType *LHSOPT,
4286 const ObjCObjectPointerType *RHSOPT,
4287 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4288
4289 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4290 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4291
4292 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4293 unsigned LHSNumProtocols = LHS->getNumProtocols();
4294 if (LHSNumProtocols > 0)
4295 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4296 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004297 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4298 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004299 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4300 LHSInheritedProtocols.end());
4301 }
4302
4303 unsigned RHSNumProtocols = RHS->getNumProtocols();
4304 if (RHSNumProtocols > 0) {
4305 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4306 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4307 if (InheritedProtocolSet.count(RHSProtocols[i]))
4308 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4309 }
4310 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004311 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004312 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004313 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4314 RHSInheritedProtocols.begin(),
4315 E = RHSInheritedProtocols.end(); I != E; ++I)
4316 if (InheritedProtocolSet.count((*I)))
4317 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004318 }
4319}
4320
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004321/// areCommonBaseCompatible - Returns common base class of the two classes if
4322/// one found. Note that this is O'2 algorithm. But it will be called as the
4323/// last type comparison in a ?-exp of ObjC pointer types before a
4324/// warning is issued. So, its invokation is extremely rare.
4325QualType ASTContext::areCommonBaseCompatible(
4326 const ObjCObjectPointerType *LHSOPT,
4327 const ObjCObjectPointerType *RHSOPT) {
4328 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4329 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4330 if (!LHS || !RHS)
4331 return QualType();
4332
4333 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4334 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4335 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004336 if (canAssignObjCInterfaces(LHS, RHS)) {
4337 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4338 getIntersectionOfProtocols(*this,
4339 LHSOPT, RHSOPT, IntersectionOfProtocols);
4340 if (IntersectionOfProtocols.empty())
4341 LHSTy = getObjCObjectPointerType(LHSTy);
4342 else
4343 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4344 IntersectionOfProtocols.size());
4345 return LHSTy;
4346 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004347 }
4348
4349 return QualType();
4350}
4351
Eli Friedman3d815e72008-08-22 00:56:42 +00004352bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4353 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004354 // Verify that the base decls are compatible: the RHS must be a subclass of
4355 // the LHS.
4356 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4357 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Chris Lattner6ac46a42008-04-07 06:51:04 +00004359 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4360 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004361 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004362 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004363
Chris Lattner6ac46a42008-04-07 06:51:04 +00004364 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4365 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004366 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004367 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004369 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4370 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004371 LHSPI != LHSPE; LHSPI++) {
4372 bool RHSImplementsProtocol = false;
4373
4374 // If the RHS doesn't implement the protocol on the left, the types
4375 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004376 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004377 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004378 RHSPI != RHSPE; RHSPI++) {
4379 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004380 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004381 break;
4382 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004383 }
4384 // FIXME: For better diagnostics, consider passing back the protocol name.
4385 if (!RHSImplementsProtocol)
4386 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004387 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004388 // The RHS implements all protocols listed on the LHS.
4389 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004390}
4391
Steve Naroff389bf462009-02-12 17:52:19 +00004392bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4393 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004394 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4395 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004396
Steve Naroff14108da2009-07-10 23:34:53 +00004397 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004398 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004399
4400 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4401 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004402}
4403
Mike Stump1eb44332009-09-09 15:08:12 +00004404/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004405/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004406/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004407/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004408bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004409 if (getLangOptions().CPlusPlus)
4410 return hasSameType(LHS, RHS);
4411
Eli Friedman3d815e72008-08-22 00:56:42 +00004412 return !mergeTypes(LHS, RHS).isNull();
4413}
4414
4415QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004416 const FunctionType *lbase = lhs->getAs<FunctionType>();
4417 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004418 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4419 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004420 bool allLTypes = true;
4421 bool allRTypes = true;
4422
4423 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004424 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004425 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004426 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004427 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004428 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004429 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004430 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004431 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4432 if (NoReturn != lbase->getNoReturnAttr())
4433 allLTypes = false;
4434 if (NoReturn != rbase->getNoReturnAttr())
4435 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004436 CallingConv lcc = lbase->getCallConv();
4437 CallingConv rcc = rbase->getCallConv();
4438 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004439 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004440 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Eli Friedman3d815e72008-08-22 00:56:42 +00004442 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004443 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4444 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004445 unsigned lproto_nargs = lproto->getNumArgs();
4446 unsigned rproto_nargs = rproto->getNumArgs();
4447
4448 // Compatible functions must have the same number of arguments
4449 if (lproto_nargs != rproto_nargs)
4450 return QualType();
4451
4452 // Variadic and non-variadic functions aren't compatible
4453 if (lproto->isVariadic() != rproto->isVariadic())
4454 return QualType();
4455
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004456 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4457 return QualType();
4458
Eli Friedman3d815e72008-08-22 00:56:42 +00004459 // Check argument compatibility
4460 llvm::SmallVector<QualType, 10> types;
4461 for (unsigned i = 0; i < lproto_nargs; i++) {
4462 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4463 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4464 QualType argtype = mergeTypes(largtype, rargtype);
4465 if (argtype.isNull()) return QualType();
4466 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004467 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4468 allLTypes = false;
4469 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4470 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004471 }
4472 if (allLTypes) return lhs;
4473 if (allRTypes) return rhs;
4474 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004475 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004476 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004477 }
4478
4479 if (lproto) allRTypes = false;
4480 if (rproto) allLTypes = false;
4481
Douglas Gregor72564e72009-02-26 23:50:07 +00004482 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004483 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004484 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004485 if (proto->isVariadic()) return QualType();
4486 // Check that the types are compatible with the types that
4487 // would result from default argument promotions (C99 6.7.5.3p15).
4488 // The only types actually affected are promotable integer
4489 // types and floats, which would be passed as a different
4490 // type depending on whether the prototype is visible.
4491 unsigned proto_nargs = proto->getNumArgs();
4492 for (unsigned i = 0; i < proto_nargs; ++i) {
4493 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004494
4495 // Look at the promotion type of enum types, since that is the type used
4496 // to pass enum values.
4497 if (const EnumType *Enum = argTy->getAs<EnumType>())
4498 argTy = Enum->getDecl()->getPromotionType();
4499
Eli Friedman3d815e72008-08-22 00:56:42 +00004500 if (argTy->isPromotableIntegerType() ||
4501 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4502 return QualType();
4503 }
4504
4505 if (allLTypes) return lhs;
4506 if (allRTypes) return rhs;
4507 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004508 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004509 proto->getTypeQuals(),
4510 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004511 }
4512
4513 if (allLTypes) return lhs;
4514 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004515 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004516}
4517
4518QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004519 // C++ [expr]: If an expression initially has the type "reference to T", the
4520 // type is adjusted to "T" prior to any further analysis, the expression
4521 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004522 // expression is an lvalue unless the reference is an rvalue reference and
4523 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004524 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4525 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4526
Eli Friedman3d815e72008-08-22 00:56:42 +00004527 QualType LHSCan = getCanonicalType(LHS),
4528 RHSCan = getCanonicalType(RHS);
4529
4530 // If two types are identical, they are compatible.
4531 if (LHSCan == RHSCan)
4532 return LHS;
4533
John McCall0953e762009-09-24 19:53:00 +00004534 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004535 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4536 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004537 if (LQuals != RQuals) {
4538 // If any of these qualifiers are different, we have a type
4539 // mismatch.
4540 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4541 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4542 return QualType();
4543
4544 // Exactly one GC qualifier difference is allowed: __strong is
4545 // okay if the other type has no GC qualifier but is an Objective
4546 // C object pointer (i.e. implicitly strong by default). We fix
4547 // this by pretending that the unqualified type was actually
4548 // qualified __strong.
4549 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4550 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4551 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4552
4553 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4554 return QualType();
4555
4556 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4557 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4558 }
4559 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4560 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4561 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004562 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004563 }
4564
4565 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004566
Eli Friedman852d63b2009-06-01 01:22:52 +00004567 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4568 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004569
Chris Lattner1adb8832008-01-14 05:45:46 +00004570 // We want to consider the two function types to be the same for these
4571 // comparisons, just force one to the other.
4572 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4573 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004574
4575 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004576 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4577 LHSClass = Type::ConstantArray;
4578 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4579 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004580
Nate Begeman213541a2008-04-18 23:10:10 +00004581 // Canonicalize ExtVector -> Vector.
4582 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4583 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004584
Chris Lattnera36a61f2008-04-07 05:43:21 +00004585 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004586 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004587 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004588 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004589 // Compatibility is based on the underlying type, not the promotion
4590 // type.
John McCall183700f2009-09-21 23:43:11 +00004591 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004592 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4593 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004594 }
John McCall183700f2009-09-21 23:43:11 +00004595 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004596 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4597 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004598 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004599
Eli Friedman3d815e72008-08-22 00:56:42 +00004600 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004601 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004602
Steve Naroff4a746782008-01-09 22:43:08 +00004603 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004604 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004605#define TYPE(Class, Base)
4606#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004607#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004608#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4609#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4610#include "clang/AST/TypeNodes.def"
4611 assert(false && "Non-canonical and dependent types shouldn't get here");
4612 return QualType();
4613
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004614 case Type::LValueReference:
4615 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004616 case Type::MemberPointer:
4617 assert(false && "C++ should never be in mergeTypes");
4618 return QualType();
4619
4620 case Type::IncompleteArray:
4621 case Type::VariableArray:
4622 case Type::FunctionProto:
4623 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004624 assert(false && "Types are eliminated above");
4625 return QualType();
4626
Chris Lattner1adb8832008-01-14 05:45:46 +00004627 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004628 {
4629 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004630 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4631 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004632 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4633 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004634 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004635 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004636 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004637 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004638 return getPointerType(ResultType);
4639 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004640 case Type::BlockPointer:
4641 {
4642 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004643 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4644 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004645 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4646 if (ResultType.isNull()) return QualType();
4647 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4648 return LHS;
4649 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4650 return RHS;
4651 return getBlockPointerType(ResultType);
4652 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004653 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004654 {
4655 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4656 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4657 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4658 return QualType();
4659
4660 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4661 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4662 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4663 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004664 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4665 return LHS;
4666 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4667 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004668 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4669 ArrayType::ArraySizeModifier(), 0);
4670 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4671 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004672 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4673 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004674 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4675 return LHS;
4676 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4677 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004678 if (LVAT) {
4679 // FIXME: This isn't correct! But tricky to implement because
4680 // the array's size has to be the size of LHS, but the type
4681 // has to be different.
4682 return LHS;
4683 }
4684 if (RVAT) {
4685 // FIXME: This isn't correct! But tricky to implement because
4686 // the array's size has to be the size of RHS, but the type
4687 // has to be different.
4688 return RHS;
4689 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004690 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4691 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004692 return getIncompleteArrayType(ResultType,
4693 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004694 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004695 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004696 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004697 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004698 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004699 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004700 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004701 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004702 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004703 case Type::Complex:
4704 // Distinct complex types are incompatible.
4705 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004706 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004707 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004708 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004709 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004710 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004711 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004712 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004713 // FIXME: This should be type compatibility, e.g. whether
4714 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004715 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4716 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004717 if (LHSIface && RHSIface &&
4718 canAssignObjCInterfaces(LHSIface, RHSIface))
4719 return LHS;
4720
Eli Friedman3d815e72008-08-22 00:56:42 +00004721 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004722 }
Steve Naroff14108da2009-07-10 23:34:53 +00004723 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004724 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4725 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004726 return LHS;
4727
Steve Naroffbc76dd02008-12-10 22:14:21 +00004728 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004729 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004730 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004731
4732 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004733}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004734
Chris Lattner5426bf62008-04-07 07:01:58 +00004735//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004736// Integer Predicates
4737//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004738
Eli Friedmanad74a752008-06-28 06:23:08 +00004739unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004740 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004741 return 1;
John McCall842aef82009-12-09 09:09:27 +00004742 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004743 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004744 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004745 return (unsigned)getTypeSize(T);
4746}
4747
4748QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4749 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004750
4751 // Turn <4 x signed int> -> <4 x unsigned int>
4752 if (const VectorType *VTy = T->getAs<VectorType>())
4753 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004754 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004755
4756 // For enums, we return the unsigned version of the base type.
4757 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004758 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004759
4760 const BuiltinType *BTy = T->getAs<BuiltinType>();
4761 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004762 switch (BTy->getKind()) {
4763 case BuiltinType::Char_S:
4764 case BuiltinType::SChar:
4765 return UnsignedCharTy;
4766 case BuiltinType::Short:
4767 return UnsignedShortTy;
4768 case BuiltinType::Int:
4769 return UnsignedIntTy;
4770 case BuiltinType::Long:
4771 return UnsignedLongTy;
4772 case BuiltinType::LongLong:
4773 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004774 case BuiltinType::Int128:
4775 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004776 default:
4777 assert(0 && "Unexpected signed integer type");
4778 return QualType();
4779 }
4780}
4781
Douglas Gregor2cf26342009-04-09 22:27:44 +00004782ExternalASTSource::~ExternalASTSource() { }
4783
4784void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004785
4786
4787//===----------------------------------------------------------------------===//
4788// Builtin Type Computation
4789//===----------------------------------------------------------------------===//
4790
4791/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4792/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004793static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004794 ASTContext::GetBuiltinTypeError &Error,
4795 bool AllowTypeModifiers = true) {
4796 // Modifiers.
4797 int HowLong = 0;
4798 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004799
Chris Lattner86df27b2009-06-14 00:45:47 +00004800 // Read the modifiers first.
4801 bool Done = false;
4802 while (!Done) {
4803 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004804 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004805 case 'S':
4806 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4807 assert(!Signed && "Can't use 'S' modifier multiple times!");
4808 Signed = true;
4809 break;
4810 case 'U':
4811 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4812 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4813 Unsigned = true;
4814 break;
4815 case 'L':
4816 assert(HowLong <= 2 && "Can't have LLLL modifier");
4817 ++HowLong;
4818 break;
4819 }
4820 }
4821
4822 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004823
Chris Lattner86df27b2009-06-14 00:45:47 +00004824 // Read the base type.
4825 switch (*Str++) {
4826 default: assert(0 && "Unknown builtin type letter!");
4827 case 'v':
4828 assert(HowLong == 0 && !Signed && !Unsigned &&
4829 "Bad modifiers used with 'v'!");
4830 Type = Context.VoidTy;
4831 break;
4832 case 'f':
4833 assert(HowLong == 0 && !Signed && !Unsigned &&
4834 "Bad modifiers used with 'f'!");
4835 Type = Context.FloatTy;
4836 break;
4837 case 'd':
4838 assert(HowLong < 2 && !Signed && !Unsigned &&
4839 "Bad modifiers used with 'd'!");
4840 if (HowLong)
4841 Type = Context.LongDoubleTy;
4842 else
4843 Type = Context.DoubleTy;
4844 break;
4845 case 's':
4846 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4847 if (Unsigned)
4848 Type = Context.UnsignedShortTy;
4849 else
4850 Type = Context.ShortTy;
4851 break;
4852 case 'i':
4853 if (HowLong == 3)
4854 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4855 else if (HowLong == 2)
4856 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4857 else if (HowLong == 1)
4858 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4859 else
4860 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4861 break;
4862 case 'c':
4863 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4864 if (Signed)
4865 Type = Context.SignedCharTy;
4866 else if (Unsigned)
4867 Type = Context.UnsignedCharTy;
4868 else
4869 Type = Context.CharTy;
4870 break;
4871 case 'b': // boolean
4872 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4873 Type = Context.BoolTy;
4874 break;
4875 case 'z': // size_t.
4876 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4877 Type = Context.getSizeType();
4878 break;
4879 case 'F':
4880 Type = Context.getCFConstantStringType();
4881 break;
4882 case 'a':
4883 Type = Context.getBuiltinVaListType();
4884 assert(!Type.isNull() && "builtin va list type not initialized!");
4885 break;
4886 case 'A':
4887 // This is a "reference" to a va_list; however, what exactly
4888 // this means depends on how va_list is defined. There are two
4889 // different kinds of va_list: ones passed by value, and ones
4890 // passed by reference. An example of a by-value va_list is
4891 // x86, where va_list is a char*. An example of by-ref va_list
4892 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4893 // we want this argument to be a char*&; for x86-64, we want
4894 // it to be a __va_list_tag*.
4895 Type = Context.getBuiltinVaListType();
4896 assert(!Type.isNull() && "builtin va list type not initialized!");
4897 if (Type->isArrayType()) {
4898 Type = Context.getArrayDecayedType(Type);
4899 } else {
4900 Type = Context.getLValueReferenceType(Type);
4901 }
4902 break;
4903 case 'V': {
4904 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004905 unsigned NumElements = strtoul(Str, &End, 10);
4906 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Chris Lattner86df27b2009-06-14 00:45:47 +00004908 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004909
Chris Lattner86df27b2009-06-14 00:45:47 +00004910 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004911 // FIXME: Don't know what to do about AltiVec.
4912 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004913 break;
4914 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004915 case 'X': {
4916 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4917 Type = Context.getComplexType(ElementType);
4918 break;
4919 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004920 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004921 Type = Context.getFILEType();
4922 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004923 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004924 return QualType();
4925 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004926 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004927 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004928 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004929 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004930 else
4931 Type = Context.getjmp_bufType();
4932
Mike Stumpfd612db2009-07-28 23:47:15 +00004933 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004934 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004935 return QualType();
4936 }
4937 break;
Mike Stump782fa302009-07-28 02:25:19 +00004938 }
Mike Stump1eb44332009-09-09 15:08:12 +00004939
Chris Lattner86df27b2009-06-14 00:45:47 +00004940 if (!AllowTypeModifiers)
4941 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004942
Chris Lattner86df27b2009-06-14 00:45:47 +00004943 Done = false;
4944 while (!Done) {
4945 switch (*Str++) {
4946 default: Done = true; --Str; break;
4947 case '*':
4948 Type = Context.getPointerType(Type);
4949 break;
4950 case '&':
4951 Type = Context.getLValueReferenceType(Type);
4952 break;
4953 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4954 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004955 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004956 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004957 case 'D':
4958 Type = Context.getVolatileType(Type);
4959 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004960 }
4961 }
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Chris Lattner86df27b2009-06-14 00:45:47 +00004963 return Type;
4964}
4965
4966/// GetBuiltinType - Return the type for the specified builtin.
4967QualType ASTContext::GetBuiltinType(unsigned id,
4968 GetBuiltinTypeError &Error) {
4969 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004970
Chris Lattner86df27b2009-06-14 00:45:47 +00004971 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004972
Chris Lattner86df27b2009-06-14 00:45:47 +00004973 Error = GE_None;
4974 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4975 if (Error != GE_None)
4976 return QualType();
4977 while (TypeStr[0] && TypeStr[0] != '.') {
4978 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4979 if (Error != GE_None)
4980 return QualType();
4981
4982 // Do array -> pointer decay. The builtin should use the decayed type.
4983 if (Ty->isArrayType())
4984 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004985
Chris Lattner86df27b2009-06-14 00:45:47 +00004986 ArgTypes.push_back(Ty);
4987 }
4988
4989 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4990 "'.' should only occur at end of builtin type list!");
4991
4992 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4993 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4994 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00004995
4996 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00004997 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004998 TypeStr[0] == '.', 0, false, false, 0, 0,
4999 false, CC_Default);
Chris Lattner86df27b2009-06-14 00:45:47 +00005000}
Eli Friedmana95d7572009-08-19 07:44:53 +00005001
5002QualType
5003ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5004 // Perform the usual unary conversions. We do this early so that
5005 // integral promotions to "int" can allow us to exit early, in the
5006 // lhs == rhs check. Also, for conversion purposes, we ignore any
5007 // qualifiers. For example, "const float" and "float" are
5008 // equivalent.
5009 if (lhs->isPromotableIntegerType())
5010 lhs = getPromotedIntegerType(lhs);
5011 else
5012 lhs = lhs.getUnqualifiedType();
5013 if (rhs->isPromotableIntegerType())
5014 rhs = getPromotedIntegerType(rhs);
5015 else
5016 rhs = rhs.getUnqualifiedType();
5017
5018 // If both types are identical, no conversion is needed.
5019 if (lhs == rhs)
5020 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005021
Eli Friedmana95d7572009-08-19 07:44:53 +00005022 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5023 // The caller can deal with this (e.g. pointer + int).
5024 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5025 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005026
5027 // At this point, we have two different arithmetic types.
5028
Eli Friedmana95d7572009-08-19 07:44:53 +00005029 // Handle complex types first (C99 6.3.1.8p1).
5030 if (lhs->isComplexType() || rhs->isComplexType()) {
5031 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005032 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005033 // convert the rhs to the lhs complex type.
5034 return lhs;
5035 }
Mike Stump1eb44332009-09-09 15:08:12 +00005036 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005037 // convert the lhs to the rhs complex type.
5038 return rhs;
5039 }
5040 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005041 // When both operands are complex, the shorter operand is converted to the
5042 // type of the longer, and that is the type of the result. This corresponds
5043 // to what is done when combining two real floating-point operands.
5044 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005045 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005046 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005047 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005048 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005049 // "double _Complex" is promoted to "long double _Complex".
5050 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005051
5052 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005053 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005054 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005055 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005056 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005057 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5058 // domains match. This is a requirement for our implementation, C99
5059 // does not require this promotion.
5060 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5061 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5062 return rhs;
5063 } else { // handle "_Complex double, double".
5064 return lhs;
5065 }
5066 }
5067 return lhs; // The domain/size match exactly.
5068 }
5069 // Now handle "real" floating types (i.e. float, double, long double).
5070 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5071 // if we have an integer operand, the result is the real floating type.
5072 if (rhs->isIntegerType()) {
5073 // convert rhs to the lhs floating point type.
5074 return lhs;
5075 }
5076 if (rhs->isComplexIntegerType()) {
5077 // convert rhs to the complex floating point type.
5078 return getComplexType(lhs);
5079 }
5080 if (lhs->isIntegerType()) {
5081 // convert lhs to the rhs floating point type.
5082 return rhs;
5083 }
Mike Stump1eb44332009-09-09 15:08:12 +00005084 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005085 // convert lhs to the complex floating point type.
5086 return getComplexType(rhs);
5087 }
5088 // We have two real floating types, float/complex combos were handled above.
5089 // Convert the smaller operand to the bigger result.
5090 int result = getFloatingTypeOrder(lhs, rhs);
5091 if (result > 0) // convert the rhs
5092 return lhs;
5093 assert(result < 0 && "illegal float comparison");
5094 return rhs; // convert the lhs
5095 }
5096 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5097 // Handle GCC complex int extension.
5098 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5099 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5100
5101 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005102 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005103 rhsComplexInt->getElementType()) >= 0)
5104 return lhs; // convert the rhs
5105 return rhs;
5106 } else if (lhsComplexInt && rhs->isIntegerType()) {
5107 // convert the rhs to the lhs complex type.
5108 return lhs;
5109 } else if (rhsComplexInt && lhs->isIntegerType()) {
5110 // convert the lhs to the rhs complex type.
5111 return rhs;
5112 }
5113 }
5114 // Finally, we have two differing integer types.
5115 // The rules for this case are in C99 6.3.1.8
5116 int compare = getIntegerTypeOrder(lhs, rhs);
5117 bool lhsSigned = lhs->isSignedIntegerType(),
5118 rhsSigned = rhs->isSignedIntegerType();
5119 QualType destType;
5120 if (lhsSigned == rhsSigned) {
5121 // Same signedness; use the higher-ranked type
5122 destType = compare >= 0 ? lhs : rhs;
5123 } else if (compare != (lhsSigned ? 1 : -1)) {
5124 // The unsigned type has greater than or equal rank to the
5125 // signed type, so use the unsigned type
5126 destType = lhsSigned ? rhs : lhs;
5127 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5128 // The two types are different widths; if we are here, that
5129 // means the signed type is larger than the unsigned type, so
5130 // use the signed type.
5131 destType = lhsSigned ? lhs : rhs;
5132 } else {
5133 // The signed type is higher-ranked than the unsigned type,
5134 // but isn't actually any bigger (like unsigned int and long
5135 // on most 32-bit systems). Use the unsigned type corresponding
5136 // to the signed type.
5137 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5138 }
5139 return destType;
5140}