blob: 079c16ac6b20e7e0b1f337e09e963ad54b26ca3e [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 }
Nuno Lopesb74668e2008-12-17 22:30:25 +000081
Ted Kremenek503524a2010-03-08 20:56:29 +000082 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
83 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
84 // Increment in loop to prevent using deallocated memory.
85 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
86 R->Destroy(*this);
87 }
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000088
Ted Kremenek503524a2010-03-08 20:56:29 +000089 for (llvm::DenseMap<const ObjCContainerDecl*,
90 const ASTRecordLayout*>::iterator
91 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
92 // Increment in loop to prevent using deallocated memory.
93 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
94 R->Destroy(*this);
95 }
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
John McCall3cb0ebd2010-03-10 03:28:59 +0000891 case Type::InjectedClassName:
892 return getTypeInfo(cast<InjectedClassNameType>(T)
893 ->getUnderlyingType().getTypePtr());
894
Douglas Gregor18857642009-04-30 17:32:17 +0000895 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000896 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000897 "Cannot request the size of a dependent type");
898 // FIXME: this is likely to be wrong once we support template
899 // aliases, since a template alias could refer to a typedef that
900 // has an __aligned__ attribute on it.
901 return getTypeInfo(getCanonicalType(T));
902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner464175b2007-07-18 17:52:12 +0000904 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000905 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000906}
907
Ken Dyckbdc601b2009-12-22 14:23:30 +0000908/// getTypeSizeInChars - Return the size of the specified type, in characters.
909/// This method does not work on incomplete types.
910CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000911 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000912}
913CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000914 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000915}
916
Ken Dyck16e20cc2010-01-26 17:25:18 +0000917/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000918/// characters. This method does not work on incomplete types.
919CharUnits ASTContext::getTypeAlignInChars(QualType T) {
920 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
921}
922CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
923 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
924}
925
Chris Lattner34ebde42009-01-27 18:08:34 +0000926/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
927/// type for the current target in bits. This can be different than the ABI
928/// alignment in cases where it is beneficial for performance to overalign
929/// a data type.
930unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
931 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000932
933 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000934 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000935 T = CT->getElementType().getTypePtr();
936 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
937 T->isSpecificBuiltinType(BuiltinType::LongLong))
938 return std::max(ABIAlign, (unsigned)getTypeSize(T));
939
Chris Lattner34ebde42009-01-27 18:08:34 +0000940 return ABIAlign;
941}
942
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000943static void CollectLocalObjCIvars(ASTContext *Ctx,
944 const ObjCInterfaceDecl *OI,
945 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000946 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
947 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000948 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000949 if (!IVDecl->isInvalidDecl())
950 Fields.push_back(cast<FieldDecl>(IVDecl));
951 }
952}
953
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000954void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
955 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
956 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
957 CollectObjCIvars(SuperClass, Fields);
958 CollectLocalObjCIvars(this, OI, Fields);
959}
960
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000961/// ShallowCollectObjCIvars -
962/// Collect all ivars, including those synthesized, in the current class.
963///
964void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000965 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000966 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
967 E = OI->ivar_end(); I != E; ++I) {
968 Ivars.push_back(*I);
969 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000970
971 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000972}
973
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000974/// CollectNonClassIvars -
975/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000976/// This includes synthesized ivars (via @synthesize) and those in
977// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000978///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000979void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000980 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000981 // Find ivars declared in class extension.
982 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
983 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
984 E = CDecl->ivar_end(); I != E; ++I) {
985 Ivars.push_back(*I);
986 }
987 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000988
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000989 // Also add any ivar defined in this class's implementation. This
990 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000991 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
992 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
993 E = ImplDecl->ivar_end(); I != E; ++I)
994 Ivars.push_back(*I);
995 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000996}
997
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000998/// CollectInheritedProtocols - Collect all protocols in current class and
999/// those inherited by it.
1000void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001001 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001002 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1003 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1004 PE = OI->protocol_end(); P != PE; ++P) {
1005 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001006 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001007 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001008 PE = Proto->protocol_end(); P != PE; ++P) {
1009 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001010 CollectInheritedProtocols(*P, Protocols);
1011 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001012 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001013
1014 // Categories of this Interface.
1015 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1016 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1017 CollectInheritedProtocols(CDeclChain, Protocols);
1018 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1019 while (SD) {
1020 CollectInheritedProtocols(SD, Protocols);
1021 SD = SD->getSuperClass();
1022 }
1023 return;
1024 }
1025 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1026 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1027 PE = OC->protocol_end(); P != PE; ++P) {
1028 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001029 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001030 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1031 PE = Proto->protocol_end(); P != PE; ++P)
1032 CollectInheritedProtocols(*P, Protocols);
1033 }
1034 return;
1035 }
1036 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1037 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1038 PE = OP->protocol_end(); P != PE; ++P) {
1039 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001040 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001041 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1042 PE = Proto->protocol_end(); P != PE; ++P)
1043 CollectInheritedProtocols(*P, Protocols);
1044 }
1045 return;
1046 }
1047}
1048
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001049unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1050 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001051 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1052 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001053 if ((*I)->getPropertyIvarDecl())
1054 ++count;
1055
1056 // Also look into nested protocols.
1057 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1058 E = PD->protocol_end(); P != E; ++P)
1059 count += CountProtocolSynthesizedIvars(*P);
1060 return count;
1061}
1062
Mike Stump1eb44332009-09-09 15:08:12 +00001063unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001064 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001065 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1066 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001067 if ((*I)->getPropertyIvarDecl())
1068 ++count;
1069 }
1070 // Also look into interface's protocol list for properties declared
1071 // in the protocol and whose ivars are synthesized.
1072 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1073 PE = OI->protocol_end(); P != PE; ++P) {
1074 ObjCProtocolDecl *PD = (*P);
1075 count += CountProtocolSynthesizedIvars(PD);
1076 }
1077 return count;
1078}
1079
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001080/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1081ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1082 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1083 I = ObjCImpls.find(D);
1084 if (I != ObjCImpls.end())
1085 return cast<ObjCImplementationDecl>(I->second);
1086 return 0;
1087}
1088/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1089ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1090 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1091 I = ObjCImpls.find(D);
1092 if (I != ObjCImpls.end())
1093 return cast<ObjCCategoryImplDecl>(I->second);
1094 return 0;
1095}
1096
1097/// \brief Set the implementation of ObjCInterfaceDecl.
1098void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1099 ObjCImplementationDecl *ImplD) {
1100 assert(IFaceD && ImplD && "Passed null params");
1101 ObjCImpls[IFaceD] = ImplD;
1102}
1103/// \brief Set the implementation of ObjCCategoryDecl.
1104void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1105 ObjCCategoryImplDecl *ImplD) {
1106 assert(CatD && ImplD && "Passed null params");
1107 ObjCImpls[CatD] = ImplD;
1108}
1109
John McCalla93c9342009-12-07 02:54:59 +00001110/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001111///
John McCalla93c9342009-12-07 02:54:59 +00001112/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001113/// the TypeLoc wrappers.
1114///
1115/// \param T the type that will be the basis for type source info. This type
1116/// should refer to how the declarator was written in source code, not to
1117/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001118TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001119 unsigned DataSize) {
1120 if (!DataSize)
1121 DataSize = TypeLoc::getFullDataSizeForType(T);
1122 else
1123 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001124 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001125
John McCalla93c9342009-12-07 02:54:59 +00001126 TypeSourceInfo *TInfo =
1127 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1128 new (TInfo) TypeSourceInfo(T);
1129 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001130}
1131
John McCalla93c9342009-12-07 02:54:59 +00001132TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001133 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001134 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001135 DI->getTypeLoc().initialize(L);
1136 return DI;
1137}
1138
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001139/// getInterfaceLayoutImpl - Get or compute information about the
1140/// layout of the given interface.
1141///
1142/// \param Impl - If given, also include the layout of the interface's
1143/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001144const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001145ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1146 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001147 assert(!D->isForwardDecl() && "Invalid interface decl!");
1148
Devang Patel44a3dde2008-06-04 21:54:36 +00001149 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001150 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001151 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1152 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1153 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001154
Daniel Dunbar453addb2009-05-03 11:16:44 +00001155 // Add in synthesized ivar count if laying out an implementation.
1156 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001157 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001158 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001159 // entry. Note we can't cache this because we simply free all
1160 // entries later; however we shouldn't look up implementations
1161 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001162 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001163 return getObjCLayout(D, 0);
1164 }
1165
Mike Stump1eb44332009-09-09 15:08:12 +00001166 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001167 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1168 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Devang Patel44a3dde2008-06-04 21:54:36 +00001170 return *NewEntry;
1171}
1172
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001173const ASTRecordLayout &
1174ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1175 return getObjCLayout(D, 0);
1176}
1177
1178const ASTRecordLayout &
1179ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1180 return getObjCLayout(D->getClassInterface(), D);
1181}
1182
Devang Patel88a981b2007-11-01 19:11:01 +00001183/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001184/// specified record (struct/union/class), which indicates its size and field
1185/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001186const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001187 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001188 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001189
Chris Lattner464175b2007-07-18 17:52:12 +00001190 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001191 // Note that we can't save a reference to the entry because this function
1192 // is recursive.
1193 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001194 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001195
Mike Stump1eb44332009-09-09 15:08:12 +00001196 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001197 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001198 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Chris Lattner5d2a6302007-07-18 18:26:58 +00001200 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001201}
1202
Anders Carlssonf53df232009-12-07 04:35:11 +00001203const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001204 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001205 assert(RD && "Cannot get key function for forward declarations!");
1206
1207 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1208 if (!Entry)
1209 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1210 else
1211 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1212 "Key function changed!");
1213
1214 return Entry;
1215}
1216
Chris Lattnera7674d82007-07-13 22:13:22 +00001217//===----------------------------------------------------------------------===//
1218// Type creation/memoization methods
1219//===----------------------------------------------------------------------===//
1220
John McCall0953e762009-09-24 19:53:00 +00001221QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1222 unsigned Fast = Quals.getFastQualifiers();
1223 Quals.removeFastQualifiers();
1224
1225 // Check if we've already instantiated this type.
1226 llvm::FoldingSetNodeID ID;
1227 ExtQuals::Profile(ID, TypeNode, Quals);
1228 void *InsertPos = 0;
1229 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1230 assert(EQ->getQualifiers() == Quals);
1231 QualType T = QualType(EQ, Fast);
1232 return T;
1233 }
1234
John McCall6b304a02009-09-24 23:30:46 +00001235 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001236 ExtQualNodes.InsertNode(New, InsertPos);
1237 QualType T = QualType(New, Fast);
1238 return T;
1239}
1240
1241QualType ASTContext::getVolatileType(QualType T) {
1242 QualType CanT = getCanonicalType(T);
1243 if (CanT.isVolatileQualified()) return T;
1244
1245 QualifierCollector Quals;
1246 const Type *TypeNode = Quals.strip(T);
1247 Quals.addVolatile();
1248
1249 return getExtQualType(TypeNode, Quals);
1250}
1251
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001252QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001253 QualType CanT = getCanonicalType(T);
1254 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001255 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001256
John McCall0953e762009-09-24 19:53:00 +00001257 // If we are composing extended qualifiers together, merge together
1258 // into one ExtQuals node.
1259 QualifierCollector Quals;
1260 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
John McCall0953e762009-09-24 19:53:00 +00001262 // If this type already has an address space specified, it cannot get
1263 // another one.
1264 assert(!Quals.hasAddressSpace() &&
1265 "Type cannot be in multiple addr spaces!");
1266 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001267
John McCall0953e762009-09-24 19:53:00 +00001268 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001269}
1270
Chris Lattnerb7d25532009-02-18 22:53:11 +00001271QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001272 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001273 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001274 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001275 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001277 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001278 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001279 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001280 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1281 return getPointerType(ResultType);
1282 }
1283 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
John McCall0953e762009-09-24 19:53:00 +00001285 // If we are composing extended qualifiers together, merge together
1286 // into one ExtQuals node.
1287 QualifierCollector Quals;
1288 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
John McCall0953e762009-09-24 19:53:00 +00001290 // If this type already has an ObjCGC specified, it cannot get
1291 // another one.
1292 assert(!Quals.hasObjCGCAttr() &&
1293 "Type cannot have multiple ObjCGCs!");
1294 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001295
John McCall0953e762009-09-24 19:53:00 +00001296 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001297}
Chris Lattnera7674d82007-07-13 22:13:22 +00001298
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001299static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1300 bool AddNoReturn,
1301 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001302 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001303 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1304 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001305 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1306 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001307 if (ResultType == Pointee)
1308 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001309
1310 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001311 } else if (const BlockPointerType *BlockPointer
1312 = T->getAs<BlockPointerType>()) {
1313 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001314 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1315 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001316 if (ResultType == Pointee)
1317 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001318
1319 ResultType = Context.getBlockPointerType(ResultType);
1320 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1321 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001322 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001323
Douglas Gregor43c79c22009-12-09 00:47:37 +00001324 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001325 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1326 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001327 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001328 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001329 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001330 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1331 FPT->getNumArgs(), FPT->isVariadic(),
1332 FPT->getTypeQuals(),
1333 FPT->hasExceptionSpec(),
1334 FPT->hasAnyExceptionSpec(),
1335 FPT->getNumExceptions(),
1336 FPT->exception_begin(),
1337 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001338 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001339 } else
1340 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001341
1342 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1343}
1344
1345QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1346 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1347}
1348
1349QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1350 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001351}
1352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353/// getComplexType - Return the uniqued reference to the type for a complex
1354/// number with the specified element type.
1355QualType ASTContext::getComplexType(QualType T) {
1356 // Unique pointers, to guarantee there is only one pointer of a particular
1357 // structure.
1358 llvm::FoldingSetNodeID ID;
1359 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 void *InsertPos = 0;
1362 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1363 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 // If the pointee type isn't canonical, this won't be a canonical type either,
1366 // so fill in the canonical type field.
1367 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001368 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001369 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // Get the new insert position for the node we care about.
1372 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001373 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 }
John McCall6b304a02009-09-24 23:30:46 +00001375 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 Types.push_back(New);
1377 ComplexTypes.InsertNode(New, InsertPos);
1378 return QualType(New, 0);
1379}
1380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381/// getPointerType - Return the uniqued reference to the type for a pointer to
1382/// the specified type.
1383QualType ASTContext::getPointerType(QualType T) {
1384 // Unique pointers, to guarantee there is only one pointer of a particular
1385 // structure.
1386 llvm::FoldingSetNodeID ID;
1387 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 void *InsertPos = 0;
1390 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1391 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 // If the pointee type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
1395 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001396 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001397 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 // Get the new insert position for the node we care about.
1400 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001401 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 }
John McCall6b304a02009-09-24 23:30:46 +00001403 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 Types.push_back(New);
1405 PointerTypes.InsertNode(New, InsertPos);
1406 return QualType(New, 0);
1407}
1408
Mike Stump1eb44332009-09-09 15:08:12 +00001409/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001410/// a pointer to the specified block.
1411QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001412 assert(T->isFunctionType() && "block of function types only");
1413 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001414 // structure.
1415 llvm::FoldingSetNodeID ID;
1416 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Steve Naroff5618bd42008-08-27 16:04:49 +00001418 void *InsertPos = 0;
1419 if (BlockPointerType *PT =
1420 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1421 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001422
1423 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001424 // type either so fill in the canonical type field.
1425 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001426 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001427 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Steve Naroff5618bd42008-08-27 16:04:49 +00001429 // Get the new insert position for the node we care about.
1430 BlockPointerType *NewIP =
1431 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001432 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001433 }
John McCall6b304a02009-09-24 23:30:46 +00001434 BlockPointerType *New
1435 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001436 Types.push_back(New);
1437 BlockPointerTypes.InsertNode(New, InsertPos);
1438 return QualType(New, 0);
1439}
1440
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001441/// getLValueReferenceType - Return the uniqued reference to the type for an
1442/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001443QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // Unique pointers, to guarantee there is only one pointer of a particular
1445 // structure.
1446 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001447 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001448
1449 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001450 if (LValueReferenceType *RT =
1451 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001453
John McCall54e14c42009-10-22 22:37:11 +00001454 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1455
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // If the referencee type isn't canonical, this won't be a canonical type
1457 // either, so fill in the canonical type field.
1458 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001459 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1460 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1461 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001464 LValueReferenceType *NewIP =
1465 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001466 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 }
1468
John McCall6b304a02009-09-24 23:30:46 +00001469 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001470 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1471 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001473 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001474
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001475 return QualType(New, 0);
1476}
1477
1478/// getRValueReferenceType - Return the uniqued reference to the type for an
1479/// rvalue reference to the specified type.
1480QualType ASTContext::getRValueReferenceType(QualType T) {
1481 // Unique pointers, to guarantee there is only one pointer of a particular
1482 // structure.
1483 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001484 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001485
1486 void *InsertPos = 0;
1487 if (RValueReferenceType *RT =
1488 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(RT, 0);
1490
John McCall54e14c42009-10-22 22:37:11 +00001491 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1492
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001493 // If the referencee type isn't canonical, this won't be a canonical type
1494 // either, so fill in the canonical type field.
1495 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001496 if (InnerRef || !T.isCanonical()) {
1497 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1498 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001499
1500 // Get the new insert position for the node we care about.
1501 RValueReferenceType *NewIP =
1502 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1503 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1504 }
1505
John McCall6b304a02009-09-24 23:30:46 +00001506 RValueReferenceType *New
1507 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001508 Types.push_back(New);
1509 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 return QualType(New, 0);
1511}
1512
Sebastian Redlf30208a2009-01-24 21:16:55 +00001513/// getMemberPointerType - Return the uniqued reference to the type for a
1514/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001515QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001516 // Unique pointers, to guarantee there is only one pointer of a particular
1517 // structure.
1518 llvm::FoldingSetNodeID ID;
1519 MemberPointerType::Profile(ID, T, Cls);
1520
1521 void *InsertPos = 0;
1522 if (MemberPointerType *PT =
1523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1524 return QualType(PT, 0);
1525
1526 // If the pointee or class type isn't canonical, this won't be a canonical
1527 // type either, so fill in the canonical type field.
1528 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001529 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001530 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1531
1532 // Get the new insert position for the node we care about.
1533 MemberPointerType *NewIP =
1534 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1535 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1536 }
John McCall6b304a02009-09-24 23:30:46 +00001537 MemberPointerType *New
1538 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001539 Types.push_back(New);
1540 MemberPointerTypes.InsertNode(New, InsertPos);
1541 return QualType(New, 0);
1542}
1543
Mike Stump1eb44332009-09-09 15:08:12 +00001544/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001545/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001546QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001547 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001548 ArrayType::ArraySizeModifier ASM,
1549 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001550 assert((EltTy->isDependentType() ||
1551 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001552 "Constant array of VLAs is illegal!");
1553
Chris Lattner38aeec72009-05-13 04:12:56 +00001554 // Convert the array size into a canonical width matching the pointer size for
1555 // the target.
1556 llvm::APInt ArySize(ArySizeIn);
1557 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001560 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001563 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001564 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 // If the element type isn't canonical, this won't be a canonical type either,
1568 // so fill in the canonical type field.
1569 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001570 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001571 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001572 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001574 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001575 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001576 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
John McCall6b304a02009-09-24 23:30:46 +00001579 ConstantArrayType *New = new(*this,TypeAlignment)
1580 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001581 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 Types.push_back(New);
1583 return QualType(New, 0);
1584}
1585
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001586/// getVariableArrayType - Returns a non-unique reference to the type for a
1587/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001588QualType ASTContext::getVariableArrayType(QualType EltTy,
1589 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001590 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001591 unsigned EltTypeQuals,
1592 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001593 // Since we don't unique expressions, it isn't possible to unique VLA's
1594 // that have an expression provided for their size.
1595
John McCall6b304a02009-09-24 23:30:46 +00001596 VariableArrayType *New = new(*this, TypeAlignment)
1597 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001598
1599 VariableArrayTypes.push_back(New);
1600 Types.push_back(New);
1601 return QualType(New, 0);
1602}
1603
Douglas Gregor898574e2008-12-05 23:32:09 +00001604/// getDependentSizedArrayType - Returns a non-unique reference to
1605/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001606/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001607QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1608 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001609 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001610 unsigned EltTypeQuals,
1611 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001612 assert((!NumElts || NumElts->isTypeDependent() ||
1613 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001614 "Size must be type- or value-dependent!");
1615
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001616 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001617 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001618 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001619
1620 if (NumElts) {
1621 // Dependently-sized array types that do not have a specified
1622 // number of elements will have their sizes deduced from an
1623 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001624 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1625 EltTypeQuals, NumElts);
1626
1627 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1628 }
1629
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001630 DependentSizedArrayType *New;
1631 if (Canon) {
1632 // We already have a canonical version of this array type; use it as
1633 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001634 New = new (*this, TypeAlignment)
1635 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1636 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001637 } else {
1638 QualType CanonEltTy = getCanonicalType(EltTy);
1639 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001640 New = new (*this, TypeAlignment)
1641 DependentSizedArrayType(*this, EltTy, QualType(),
1642 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001643
Douglas Gregor789b1f62010-02-04 18:10:26 +00001644 if (NumElts) {
1645 DependentSizedArrayType *CanonCheck
1646 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1647 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1648 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001649 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001650 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001651 } else {
1652 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1653 ASM, EltTypeQuals,
1654 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001655 New = new (*this, TypeAlignment)
1656 DependentSizedArrayType(*this, EltTy, Canon,
1657 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001658 }
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Douglas Gregor898574e2008-12-05 23:32:09 +00001661 Types.push_back(New);
1662 return QualType(New, 0);
1663}
1664
Eli Friedmanc5773c42008-02-15 18:16:39 +00001665QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1666 ArrayType::ArraySizeModifier ASM,
1667 unsigned EltTypeQuals) {
1668 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001669 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001670
1671 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001672 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001673 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1674 return QualType(ATP, 0);
1675
1676 // If the element type isn't canonical, this won't be a canonical type
1677 // either, so fill in the canonical type field.
1678 QualType Canonical;
1679
John McCall467b27b2009-10-22 20:10:53 +00001680 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001681 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001682 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001683
1684 // Get the new insert position for the node we care about.
1685 IncompleteArrayType *NewIP =
1686 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001687 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001688 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001689
John McCall6b304a02009-09-24 23:30:46 +00001690 IncompleteArrayType *New = new (*this, TypeAlignment)
1691 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001692
1693 IncompleteArrayTypes.InsertNode(New, InsertPos);
1694 Types.push_back(New);
1695 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001696}
1697
Steve Naroff73322922007-07-18 18:00:27 +00001698/// getVectorType - Return the unique reference to a vector type of
1699/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001700QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1701 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Chris Lattnerf52ab252008-04-06 22:59:24 +00001704 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001705 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // Check if we've already instantiated a vector of this type.
1708 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001709 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1710 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 void *InsertPos = 0;
1712 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1713 return QualType(VTP, 0);
1714
1715 // If the element type isn't canonical, this won't be a canonical type either,
1716 // so fill in the canonical type field.
1717 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001718 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1719 Canonical = getVectorType(getCanonicalType(vecType),
1720 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 // Get the new insert position for the node we care about.
1723 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001724 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 }
John McCall6b304a02009-09-24 23:30:46 +00001726 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001727 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 VectorTypes.InsertNode(New, InsertPos);
1729 Types.push_back(New);
1730 return QualType(New, 0);
1731}
1732
Nate Begeman213541a2008-04-18 23:10:10 +00001733/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001734/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001735QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001736 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Chris Lattnerf52ab252008-04-06 22:59:24 +00001738 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001739 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Steve Naroff73322922007-07-18 18:00:27 +00001741 // Check if we've already instantiated a vector of this type.
1742 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001743 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001744 void *InsertPos = 0;
1745 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1746 return QualType(VTP, 0);
1747
1748 // If the element type isn't canonical, this won't be a canonical type either,
1749 // so fill in the canonical type field.
1750 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001751 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001752 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Steve Naroff73322922007-07-18 18:00:27 +00001754 // Get the new insert position for the node we care about.
1755 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001756 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001757 }
John McCall6b304a02009-09-24 23:30:46 +00001758 ExtVectorType *New = new (*this, TypeAlignment)
1759 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001760 VectorTypes.InsertNode(New, InsertPos);
1761 Types.push_back(New);
1762 return QualType(New, 0);
1763}
1764
Mike Stump1eb44332009-09-09 15:08:12 +00001765QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001766 Expr *SizeExpr,
1767 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001768 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001769 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001770 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001772 void *InsertPos = 0;
1773 DependentSizedExtVectorType *Canon
1774 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1775 DependentSizedExtVectorType *New;
1776 if (Canon) {
1777 // We already have a canonical version of this array type; use it as
1778 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001779 New = new (*this, TypeAlignment)
1780 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1781 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001782 } else {
1783 QualType CanonVecTy = getCanonicalType(vecType);
1784 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001785 New = new (*this, TypeAlignment)
1786 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1787 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001788
1789 DependentSizedExtVectorType *CanonCheck
1790 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1791 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1792 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001793 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1794 } else {
1795 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1796 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001797 New = new (*this, TypeAlignment)
1798 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001799 }
1800 }
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001802 Types.push_back(New);
1803 return QualType(New, 0);
1804}
1805
Douglas Gregor72564e72009-02-26 23:50:07 +00001806/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001807///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001808QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1809 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 // Unique functions, to guarantee there is only one function of a particular
1811 // structure.
1812 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001813 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001816 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001817 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001821 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001822 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001823 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001824 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001827 FunctionNoProtoType *NewIP =
1828 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001829 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
John McCall6b304a02009-09-24 23:30:46 +00001832 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001833 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001835 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 return QualType(New, 0);
1837}
1838
1839/// getFunctionType - Return a normal function type with a typed argument
1840/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001841QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001842 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001843 unsigned TypeQuals, bool hasExceptionSpec,
1844 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001845 const QualType *ExArray, bool NoReturn,
1846 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 // Unique functions, to guarantee there is only one function of a particular
1848 // structure.
1849 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001850 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001851 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001852 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001853
1854 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001855 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001856 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001858
1859 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001860 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001862 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 isCanonical = false;
1864
1865 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001866 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001868 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 llvm::SmallVector<QualType, 16> CanonicalArgs;
1870 CanonicalArgs.reserve(NumArgs);
1871 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001872 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001873
Chris Lattnerf52ab252008-04-06 22:59:24 +00001874 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001875 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001876 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001877 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001878 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001879
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001881 FunctionProtoType *NewIP =
1882 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001883 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001885
Douglas Gregor72564e72009-02-26 23:50:07 +00001886 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001887 // for two variable size arrays (for parameter and exception types) at the
1888 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001889 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001890 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1891 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001892 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001893 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001894 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001895 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001897 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 return QualType(FTP, 0);
1899}
1900
John McCall3cb0ebd2010-03-10 03:28:59 +00001901#ifndef NDEBUG
1902static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1903 if (!isa<CXXRecordDecl>(D)) return false;
1904 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1905 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1906 return true;
1907 if (RD->getDescribedClassTemplate() &&
1908 !isa<ClassTemplateSpecializationDecl>(RD))
1909 return true;
1910 return false;
1911}
1912#endif
1913
1914/// getInjectedClassNameType - Return the unique reference to the
1915/// injected class name type for the specified templated declaration.
1916QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1917 QualType TST) {
1918 assert(NeedsInjectedClassNameType(Decl));
1919 if (Decl->TypeForDecl) {
1920 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1921 } else if (CXXRecordDecl *PrevDecl
1922 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1923 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1924 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1925 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1926 } else {
1927 Decl->TypeForDecl = new (*this, TypeAlignment)
1928 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1929 Types.push_back(Decl->TypeForDecl);
1930 }
1931 return QualType(Decl->TypeForDecl, 0);
1932}
1933
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001934/// getTypeDeclType - Return the unique reference to the type for the
1935/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001936QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001937 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001938 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001939
John McCall19c85762010-02-16 03:57:14 +00001940 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001941 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001942
1943 if (const ObjCInterfaceDecl *ObjCInterface
Mike Stump9fdbab32009-07-31 02:02:20 +00001944 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001945 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001946
John McCallbecb8d52010-03-10 06:48:02 +00001947 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1948 "Template type parameter types are always available.");
1949
John McCall19c85762010-02-16 03:57:14 +00001950 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001951 assert(!Record->getPreviousDeclaration() &&
1952 "struct/union has previous declaration");
1953 assert(!NeedsInjectedClassNameType(Record));
1954 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001955 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001956 assert(!Enum->getPreviousDeclaration() &&
1957 "enum has previous declaration");
1958 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001959 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001960 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1961 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001962 } else
John McCallbecb8d52010-03-10 06:48:02 +00001963 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001964
John McCallbecb8d52010-03-10 06:48:02 +00001965 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001966 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001967}
1968
Reid Spencer5f016e22007-07-11 17:01:13 +00001969/// getTypedefType - Return the unique reference to the type for the
1970/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001971QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Chris Lattnerf52ab252008-04-06 22:59:24 +00001974 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001975 Decl->TypeForDecl = new(*this, TypeAlignment)
1976 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 Types.push_back(Decl->TypeForDecl);
1978 return QualType(Decl->TypeForDecl, 0);
1979}
1980
John McCall49a832b2009-10-18 09:09:24 +00001981/// \brief Retrieve a substitution-result type.
1982QualType
1983ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1984 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001985 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001986 && "replacement types must always be canonical");
1987
1988 llvm::FoldingSetNodeID ID;
1989 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1990 void *InsertPos = 0;
1991 SubstTemplateTypeParmType *SubstParm
1992 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1993
1994 if (!SubstParm) {
1995 SubstParm = new (*this, TypeAlignment)
1996 SubstTemplateTypeParmType(Parm, Replacement);
1997 Types.push_back(SubstParm);
1998 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1999 }
2000
2001 return QualType(SubstParm, 0);
2002}
2003
Douglas Gregorfab9d672009-02-05 23:33:38 +00002004/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002005/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002006/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002007QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002008 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00002009 IdentifierInfo *Name) {
2010 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002011 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002012 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002013 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002014 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2015
2016 if (TypeParm)
2017 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002019 if (Name) {
2020 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00002021 TypeParm = new (*this, TypeAlignment)
2022 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002023
2024 TemplateTypeParmType *TypeCheck
2025 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2026 assert(!TypeCheck && "Template type parameter canonical type broken");
2027 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002028 } else
John McCall6b304a02009-09-24 23:30:46 +00002029 TypeParm = new (*this, TypeAlignment)
2030 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002031
2032 Types.push_back(TypeParm);
2033 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2034
2035 return QualType(TypeParm, 0);
2036}
2037
John McCall3cb0ebd2010-03-10 03:28:59 +00002038TypeSourceInfo *
2039ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2040 SourceLocation NameLoc,
2041 const TemplateArgumentListInfo &Args,
2042 QualType CanonType) {
2043 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2044
2045 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2046 TemplateSpecializationTypeLoc TL
2047 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2048 TL.setTemplateNameLoc(NameLoc);
2049 TL.setLAngleLoc(Args.getLAngleLoc());
2050 TL.setRAngleLoc(Args.getRAngleLoc());
2051 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2052 TL.setArgLocInfo(i, Args[i].getLocInfo());
2053 return DI;
2054}
2055
Mike Stump1eb44332009-09-09 15:08:12 +00002056QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002057ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002058 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00002059 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00002060 unsigned NumArgs = Args.size();
2061
John McCall833ca992009-10-29 08:12:44 +00002062 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2063 ArgVec.reserve(NumArgs);
2064 for (unsigned i = 0; i != NumArgs; ++i)
2065 ArgVec.push_back(Args[i].getArgument());
2066
2067 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2068}
2069
2070QualType
2071ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002072 const TemplateArgument *Args,
2073 unsigned NumArgs,
2074 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002075 if (!Canon.isNull())
2076 Canon = getCanonicalType(Canon);
2077 else {
2078 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00002079 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2080 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2081 CanonArgs.reserve(NumArgs);
2082 for (unsigned I = 0; I != NumArgs; ++I)
2083 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2084
2085 // Determine whether this canonical template specialization type already
2086 // exists.
2087 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002088 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00002089 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002090
2091 void *InsertPos = 0;
2092 TemplateSpecializationType *Spec
2093 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Douglas Gregor1275ae02009-07-28 23:00:59 +00002095 if (!Spec) {
2096 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00002097 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00002098 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002099 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002100 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00002101 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00002102 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002103 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002104 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregorb88e8882009-07-30 17:40:51 +00002107 if (Canon.isNull())
2108 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002109 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00002110 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00002111 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002112
Douglas Gregor1275ae02009-07-28 23:00:59 +00002113 // Allocate the (non-canonical) template specialization type, but don't
2114 // try to unique it: these types typically have location information that
2115 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002116 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002117 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002118 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002119 TemplateSpecializationType *Spec
2120 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002121 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Douglas Gregor55f6b142009-02-09 18:46:07 +00002123 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002124 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002125}
2126
Mike Stump1eb44332009-09-09 15:08:12 +00002127QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00002128ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00002129 QualType NamedType) {
2130 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00002131 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002132
2133 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002134 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00002135 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2136 if (T)
2137 return QualType(T, 0);
2138
Douglas Gregor789b1f62010-02-04 18:10:26 +00002139 QualType Canon = NamedType;
2140 if (!Canon.isCanonical()) {
2141 Canon = getCanonicalType(NamedType);
2142 QualifiedNameType *CheckT
2143 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2144 assert(!CheckT && "Qualified name canonical type broken");
2145 (void)CheckT;
2146 }
2147
2148 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002149 Types.push_back(T);
2150 QualifiedNameTypes.InsertNode(T, InsertPos);
2151 return QualType(T, 0);
2152}
2153
Mike Stump1eb44332009-09-09 15:08:12 +00002154QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002155 const IdentifierInfo *Name,
2156 QualType Canon) {
2157 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2158
2159 if (Canon.isNull()) {
2160 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2161 if (CanonNNS != NNS)
2162 Canon = getTypenameType(CanonNNS, Name);
2163 }
2164
2165 llvm::FoldingSetNodeID ID;
2166 TypenameType::Profile(ID, NNS, Name);
2167
2168 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002169 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002170 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2171 if (T)
2172 return QualType(T, 0);
2173
2174 T = new (*this) TypenameType(NNS, Name, Canon);
2175 Types.push_back(T);
2176 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002177 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002178}
2179
Mike Stump1eb44332009-09-09 15:08:12 +00002180QualType
2181ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002182 const TemplateSpecializationType *TemplateId,
2183 QualType Canon) {
2184 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2185
Douglas Gregor789b1f62010-02-04 18:10:26 +00002186 llvm::FoldingSetNodeID ID;
2187 TypenameType::Profile(ID, NNS, TemplateId);
2188
2189 void *InsertPos = 0;
2190 TypenameType *T
2191 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2192 if (T)
2193 return QualType(T, 0);
2194
Douglas Gregor17343172009-04-01 00:28:59 +00002195 if (Canon.isNull()) {
2196 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2197 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2198 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2199 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002200 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002201 assert(CanonTemplateId &&
2202 "Canonical type must also be a template specialization type");
2203 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2204 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002205
2206 TypenameType *CheckT
2207 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2208 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002209 }
2210
Douglas Gregor17343172009-04-01 00:28:59 +00002211 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2212 Types.push_back(T);
2213 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002214 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002215}
2216
John McCall7da24312009-09-05 00:15:47 +00002217QualType
2218ASTContext::getElaboratedType(QualType UnderlyingType,
2219 ElaboratedType::TagKind Tag) {
2220 llvm::FoldingSetNodeID ID;
2221 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002222
John McCall7da24312009-09-05 00:15:47 +00002223 void *InsertPos = 0;
2224 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2225 if (T)
2226 return QualType(T, 0);
2227
Douglas Gregor789b1f62010-02-04 18:10:26 +00002228 QualType Canon = UnderlyingType;
2229 if (!Canon.isCanonical()) {
2230 Canon = getCanonicalType(Canon);
2231 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2233 }
John McCall7da24312009-09-05 00:15:47 +00002234
2235 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2236 Types.push_back(T);
2237 ElaboratedTypes.InsertNode(T, InsertPos);
2238 return QualType(T, 0);
2239}
2240
Chris Lattner88cb27a2008-04-07 04:56:42 +00002241/// CmpProtocolNames - Comparison predicate for sorting protocols
2242/// alphabetically.
2243static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2244 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002245 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002246}
2247
John McCall54e14c42009-10-22 22:37:11 +00002248static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2249 unsigned NumProtocols) {
2250 if (NumProtocols == 0) return true;
2251
2252 for (unsigned i = 1; i != NumProtocols; ++i)
2253 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2254 return false;
2255 return true;
2256}
2257
2258static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002259 unsigned &NumProtocols) {
2260 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Chris Lattner88cb27a2008-04-07 04:56:42 +00002262 // Sort protocols, keyed by name.
2263 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2264
2265 // Remove duplicates.
2266 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2267 NumProtocols = ProtocolsEnd-Protocols;
2268}
2269
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002270/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2271/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002272QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002273 ObjCProtocolDecl **Protocols,
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002274 unsigned NumProtocols,
2275 unsigned Quals) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002276 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002277 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002278 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002279
2280 void *InsertPos = 0;
2281 if (ObjCObjectPointerType *QT =
2282 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002283 return getQualifiedType(QualType(QT, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002284
John McCall54e14c42009-10-22 22:37:11 +00002285 // Sort the protocol list alphabetically to canonicalize it.
2286 QualType Canonical;
2287 if (!InterfaceT.isCanonical() ||
2288 !areSortedAndUniqued(Protocols, NumProtocols)) {
2289 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2290 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2291 unsigned UniqueCount = NumProtocols;
2292
2293 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2294 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2295
2296 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2297 &Sorted[0], UniqueCount);
2298 } else {
2299 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2300 Protocols, NumProtocols);
2301 }
2302
2303 // Regenerate InsertPos.
2304 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2305 }
2306
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002307 // No match.
2308 unsigned Size = sizeof(ObjCObjectPointerType)
2309 + NumProtocols * sizeof(ObjCProtocolDecl *);
2310 void *Mem = Allocate(Size, TypeAlignment);
2311 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2312 InterfaceT,
2313 Protocols,
2314 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002316 Types.push_back(QType);
2317 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002318 return getQualifiedType(QualType(QType, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002319}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002320
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002321/// getObjCInterfaceType - Return the unique reference to the type for the
2322/// specified ObjC interface decl. The list of protocols is optional.
2323QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002324 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002325 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002326 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002328 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002329 if (ObjCInterfaceType *QT =
2330 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002331 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002332
John McCall54e14c42009-10-22 22:37:11 +00002333 // Sort the protocol list alphabetically to canonicalize it.
2334 QualType Canonical;
2335 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2336 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2337 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2338
2339 unsigned UniqueCount = NumProtocols;
2340 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2341
2342 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2343
2344 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2345 }
2346
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002347 unsigned Size = sizeof(ObjCInterfaceType)
2348 + NumProtocols * sizeof(ObjCProtocolDecl *);
2349 void *Mem = Allocate(Size, TypeAlignment);
2350 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2351 const_cast<ObjCInterfaceDecl*>(Decl),
2352 Protocols,
2353 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002354
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002355 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002356 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002357 return QualType(QType, 0);
2358}
2359
Douglas Gregor72564e72009-02-26 23:50:07 +00002360/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2361/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002362/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002363/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002364/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002365QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002366 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002367 if (tofExpr->isTypeDependent()) {
2368 llvm::FoldingSetNodeID ID;
2369 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Douglas Gregorb1975722009-07-30 23:18:24 +00002371 void *InsertPos = 0;
2372 DependentTypeOfExprType *Canon
2373 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2374 if (Canon) {
2375 // We already have a "canonical" version of an identical, dependent
2376 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002377 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002378 QualType((TypeOfExprType*)Canon, 0));
2379 }
2380 else {
2381 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002382 Canon
2383 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002384 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2385 toe = Canon;
2386 }
2387 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002388 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002389 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002390 }
Steve Naroff9752f252007-08-01 18:02:17 +00002391 Types.push_back(toe);
2392 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002393}
2394
Steve Naroff9752f252007-08-01 18:02:17 +00002395/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2396/// TypeOfType AST's. The only motivation to unique these nodes would be
2397/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002398/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002399/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002400QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002401 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002402 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002403 Types.push_back(tot);
2404 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002405}
2406
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002407/// getDecltypeForExpr - Given an expr, will return the decltype for that
2408/// expression, according to the rules in C++0x [dcl.type.simple]p4
2409static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002410 if (e->isTypeDependent())
2411 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002413 // If e is an id expression or a class member access, decltype(e) is defined
2414 // as the type of the entity named by e.
2415 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2416 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2417 return VD->getType();
2418 }
2419 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2420 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2421 return FD->getType();
2422 }
2423 // If e is a function call or an invocation of an overloaded operator,
2424 // (parentheses around e are ignored), decltype(e) is defined as the
2425 // return type of that function.
2426 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2427 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002429 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002430
2431 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002432 // defined as T&, otherwise decltype(e) is defined as T.
2433 if (e->isLvalue(Context) == Expr::LV_Valid)
2434 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002436 return T;
2437}
2438
Anders Carlsson395b4752009-06-24 19:06:50 +00002439/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2440/// DecltypeType AST's. The only motivation to unique these nodes would be
2441/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002442/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002443/// on canonical type's (which are always unique).
2444QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002445 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002446 if (e->isTypeDependent()) {
2447 llvm::FoldingSetNodeID ID;
2448 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002450 void *InsertPos = 0;
2451 DependentDecltypeType *Canon
2452 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2453 if (Canon) {
2454 // We already have a "canonical" version of an equivalent, dependent
2455 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002456 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002457 QualType((DecltypeType*)Canon, 0));
2458 }
2459 else {
2460 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002461 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002462 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2463 dt = Canon;
2464 }
2465 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002466 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002467 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002468 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002469 Types.push_back(dt);
2470 return QualType(dt, 0);
2471}
2472
Reid Spencer5f016e22007-07-11 17:01:13 +00002473/// getTagDeclType - Return the unique reference to the type for the
2474/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002475QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002476 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002477 // FIXME: What is the design on getTagDeclType when it requires casting
2478 // away const? mutable?
2479 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002480}
2481
Mike Stump1eb44332009-09-09 15:08:12 +00002482/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2483/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2484/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002485CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002486 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002487}
2488
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002489/// getSignedWCharType - Return the type of "signed wchar_t".
2490/// Used when in C++, as a GCC extension.
2491QualType ASTContext::getSignedWCharType() const {
2492 // FIXME: derive from "Target" ?
2493 return WCharTy;
2494}
2495
2496/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2497/// Used when in C++, as a GCC extension.
2498QualType ASTContext::getUnsignedWCharType() const {
2499 // FIXME: derive from "Target" ?
2500 return UnsignedIntTy;
2501}
2502
Chris Lattner8b9023b2007-07-13 03:05:23 +00002503/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2504/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2505QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002506 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002507}
2508
Chris Lattnere6327742008-04-02 05:18:44 +00002509//===----------------------------------------------------------------------===//
2510// Type Operators
2511//===----------------------------------------------------------------------===//
2512
John McCall54e14c42009-10-22 22:37:11 +00002513CanQualType ASTContext::getCanonicalParamType(QualType T) {
2514 // Push qualifiers into arrays, and then discard any remaining
2515 // qualifiers.
2516 T = getCanonicalType(T);
2517 const Type *Ty = T.getTypePtr();
2518
2519 QualType Result;
2520 if (isa<ArrayType>(Ty)) {
2521 Result = getArrayDecayedType(QualType(Ty,0));
2522 } else if (isa<FunctionType>(Ty)) {
2523 Result = getPointerType(QualType(Ty, 0));
2524 } else {
2525 Result = QualType(Ty, 0);
2526 }
2527
2528 return CanQualType::CreateUnsafe(Result);
2529}
2530
Chris Lattner77c96472008-04-06 22:41:35 +00002531/// getCanonicalType - Return the canonical (structural) type corresponding to
2532/// the specified potentially non-canonical type. The non-canonical version
2533/// of a type may have many "decorated" versions of types. Decorators can
2534/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2535/// to be free of any of these, allowing two canonical types to be compared
2536/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002537CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002538 QualifierCollector Quals;
2539 const Type *Ptr = Quals.strip(T);
2540 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002541
John McCall0953e762009-09-24 19:53:00 +00002542 // The canonical internal type will be the canonical type *except*
2543 // that we push type qualifiers down through array types.
2544
2545 // If there are no new qualifiers to push down, stop here.
2546 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002547 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002548
John McCall0953e762009-09-24 19:53:00 +00002549 // If the type qualifiers are on an array type, get the canonical
2550 // type of the array with the qualifiers applied to the element
2551 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002552 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2553 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002554 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002556 // Get the canonical version of the element with the extra qualifiers on it.
2557 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002558 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002559 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002560
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002561 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002562 return CanQualType::CreateUnsafe(
2563 getConstantArrayType(NewEltTy, CAT->getSize(),
2564 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002565 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002566 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002567 return CanQualType::CreateUnsafe(
2568 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002569 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Douglas Gregor898574e2008-12-05 23:32:09 +00002571 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002572 return CanQualType::CreateUnsafe(
2573 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002574 DSAT->getSizeExpr() ?
2575 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002576 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002577 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002578 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002579
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002580 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002581 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002582 VAT->getSizeExpr() ?
2583 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002584 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002585 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002586 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002587}
2588
Chandler Carruth28e318c2009-12-29 07:16:59 +00002589QualType ASTContext::getUnqualifiedArrayType(QualType T,
2590 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002591 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002592 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002593 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002594 }
2595
Chandler Carruth28e318c2009-12-29 07:16:59 +00002596 const ArrayType *AT = cast<ArrayType>(T);
2597 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002598 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002599 if (Elt == UnqualElt)
2600 return T;
2601
2602 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2603 return getConstantArrayType(UnqualElt, CAT->getSize(),
2604 CAT->getSizeModifier(), 0);
2605 }
2606
2607 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2608 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2609 }
2610
2611 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2612 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2613 DSAT->getSizeModifier(), 0,
2614 SourceRange());
2615}
2616
John McCall80ad16f2009-11-24 18:42:40 +00002617DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2618 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2619 return TD->getDeclName();
2620
2621 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2622 if (DTN->isIdentifier()) {
2623 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2624 } else {
2625 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2626 }
2627 }
2628
John McCall0bd6feb2009-12-02 08:04:21 +00002629 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2630 assert(Storage);
2631 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002632}
2633
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002634TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2635 // If this template name refers to a template, the canonical
2636 // template name merely stores the template itself.
2637 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002638 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002639
John McCall0bd6feb2009-12-02 08:04:21 +00002640 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002642 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2643 assert(DTN && "Non-dependent template names must refer to template decls.");
2644 return DTN->CanonicalTemplateName;
2645}
2646
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002647bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2648 X = getCanonicalTemplateName(X);
2649 Y = getCanonicalTemplateName(Y);
2650 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2651}
2652
Mike Stump1eb44332009-09-09 15:08:12 +00002653TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002654ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2655 switch (Arg.getKind()) {
2656 case TemplateArgument::Null:
2657 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Douglas Gregor1275ae02009-07-28 23:00:59 +00002659 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002660 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Douglas Gregor1275ae02009-07-28 23:00:59 +00002662 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002663 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002664
Douglas Gregor788cd062009-11-11 01:00:40 +00002665 case TemplateArgument::Template:
2666 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2667
Douglas Gregor1275ae02009-07-28 23:00:59 +00002668 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002669 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002670 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Douglas Gregor1275ae02009-07-28 23:00:59 +00002672 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002673 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Douglas Gregor1275ae02009-07-28 23:00:59 +00002675 case TemplateArgument::Pack: {
2676 // FIXME: Allocate in ASTContext
2677 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2678 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002679 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002680 AEnd = Arg.pack_end();
2681 A != AEnd; (void)++A, ++Idx)
2682 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregor1275ae02009-07-28 23:00:59 +00002684 TemplateArgument Result;
2685 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2686 return Result;
2687 }
2688 }
2689
2690 // Silence GCC warning
2691 assert(false && "Unhandled template argument kind");
2692 return TemplateArgument();
2693}
2694
Douglas Gregord57959a2009-03-27 23:10:48 +00002695NestedNameSpecifier *
2696ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002697 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002698 return 0;
2699
2700 switch (NNS->getKind()) {
2701 case NestedNameSpecifier::Identifier:
2702 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002703 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002704 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2705 NNS->getAsIdentifier());
2706
2707 case NestedNameSpecifier::Namespace:
2708 // A namespace is canonical; build a nested-name-specifier with
2709 // this namespace and no prefix.
2710 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2711
2712 case NestedNameSpecifier::TypeSpec:
2713 case NestedNameSpecifier::TypeSpecWithTemplate: {
2714 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002715 return NestedNameSpecifier::Create(*this, 0,
2716 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002717 T.getTypePtr());
2718 }
2719
2720 case NestedNameSpecifier::Global:
2721 // The global specifier is canonical and unique.
2722 return NNS;
2723 }
2724
2725 // Required to silence a GCC warning
2726 return 0;
2727}
2728
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002729
2730const ArrayType *ASTContext::getAsArrayType(QualType T) {
2731 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002732 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002733 // Handle the common positive case fast.
2734 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2735 return AT;
2736 }
Mike Stump1eb44332009-09-09 15:08:12 +00002737
John McCall0953e762009-09-24 19:53:00 +00002738 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002739 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002740 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002741 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002742
John McCall0953e762009-09-24 19:53:00 +00002743 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002744 // implements C99 6.7.3p8: "If the specification of an array type includes
2745 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002747 // If we get here, we either have type qualifiers on the type, or we have
2748 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002749 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002750
John McCall0953e762009-09-24 19:53:00 +00002751 QualifierCollector Qs;
2752 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002754 // If we have a simple case, just return now.
2755 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002756 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002757 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002759 // Otherwise, we have an array and we have qualifiers on it. Push the
2760 // qualifiers into the array element type and return a new array type.
2761 // Get the canonical version of the element with the extra qualifiers on it.
2762 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002763 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002765 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2766 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2767 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002768 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002769 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2770 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2771 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002772 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002773
Mike Stump1eb44332009-09-09 15:08:12 +00002774 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002775 = dyn_cast<DependentSizedArrayType>(ATy))
2776 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002777 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002778 DSAT->getSizeExpr() ?
2779 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002780 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002781 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002782 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002784 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002785 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002786 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002787 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002788 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002789 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002790 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002791}
2792
2793
Chris Lattnere6327742008-04-02 05:18:44 +00002794/// getArrayDecayedType - Return the properly qualified result of decaying the
2795/// specified array type to a pointer. This operation is non-trivial when
2796/// handling typedefs etc. The canonical type of "T" must be an array type,
2797/// this returns a pointer to a properly qualified element of the array.
2798///
2799/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2800QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002801 // Get the element type with 'getAsArrayType' so that we don't lose any
2802 // typedefs in the element type of the array. This also handles propagation
2803 // of type qualifiers from the array type into the element type if present
2804 // (C99 6.7.3p8).
2805 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2806 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002808 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002809
2810 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002811 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002812}
2813
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002814QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002815 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002816 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002817 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002818 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2819 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002820 } else {
John McCall0953e762009-09-24 19:53:00 +00002821 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002822 }
2823 }
2824}
2825
Anders Carlssonfbbce492009-09-25 01:23:32 +00002826QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2827 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Anders Carlssonfbbce492009-09-25 01:23:32 +00002829 if (const ArrayType *AT = getAsArrayType(ElemTy))
2830 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Anders Carlsson6183a992008-12-21 03:44:36 +00002832 return ElemTy;
2833}
2834
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002835/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002836uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002837ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2838 uint64_t ElementCount = 1;
2839 do {
2840 ElementCount *= CA->getSize().getZExtValue();
2841 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2842 } while (CA);
2843 return ElementCount;
2844}
2845
Reid Spencer5f016e22007-07-11 17:01:13 +00002846/// getFloatingRank - Return a relative rank for floating point types.
2847/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002848static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002849 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002851
John McCall183700f2009-09-21 23:43:11 +00002852 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2853 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002854 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 case BuiltinType::Float: return FloatRank;
2856 case BuiltinType::Double: return DoubleRank;
2857 case BuiltinType::LongDouble: return LongDoubleRank;
2858 }
2859}
2860
Mike Stump1eb44332009-09-09 15:08:12 +00002861/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2862/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002863/// 'typeDomain' is a real floating point or complex type.
2864/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002865QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2866 QualType Domain) const {
2867 FloatingRank EltRank = getFloatingRank(Size);
2868 if (Domain->isComplexType()) {
2869 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002870 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002871 case FloatRank: return FloatComplexTy;
2872 case DoubleRank: return DoubleComplexTy;
2873 case LongDoubleRank: return LongDoubleComplexTy;
2874 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002875 }
Chris Lattner1361b112008-04-06 23:58:54 +00002876
2877 assert(Domain->isRealFloatingType() && "Unknown domain!");
2878 switch (EltRank) {
2879 default: assert(0 && "getFloatingRank(): illegal value for rank");
2880 case FloatRank: return FloatTy;
2881 case DoubleRank: return DoubleTy;
2882 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002883 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002884}
2885
Chris Lattner7cfeb082008-04-06 23:55:33 +00002886/// getFloatingTypeOrder - Compare the rank of the two specified floating
2887/// point types, ignoring the domain of the type (i.e. 'double' ==
2888/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002889/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002890int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2891 FloatingRank LHSR = getFloatingRank(LHS);
2892 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Chris Lattnera75cea32008-04-06 23:38:49 +00002894 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002895 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002896 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002897 return 1;
2898 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002899}
2900
Chris Lattnerf52ab252008-04-06 22:59:24 +00002901/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2902/// routine will assert if passed a built-in type that isn't an integer or enum,
2903/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002904unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002905 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002906 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002907 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002908
Eli Friedmana3426752009-07-05 23:44:27 +00002909 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2910 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2911
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002912 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2913 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2914
2915 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2916 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2917
Chris Lattnerf52ab252008-04-06 22:59:24 +00002918 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002919 default: assert(0 && "getIntegerRank(): not a built-in integer");
2920 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002921 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002922 case BuiltinType::Char_S:
2923 case BuiltinType::Char_U:
2924 case BuiltinType::SChar:
2925 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002926 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002927 case BuiltinType::Short:
2928 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002929 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002930 case BuiltinType::Int:
2931 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002932 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002933 case BuiltinType::Long:
2934 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002935 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002936 case BuiltinType::LongLong:
2937 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002938 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002939 case BuiltinType::Int128:
2940 case BuiltinType::UInt128:
2941 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002942 }
2943}
2944
Eli Friedman04e83572009-08-20 04:21:42 +00002945/// \brief Whether this is a promotable bitfield reference according
2946/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2947///
2948/// \returns the type this bit-field will promote to, or NULL if no
2949/// promotion occurs.
2950QualType ASTContext::isPromotableBitField(Expr *E) {
2951 FieldDecl *Field = E->getBitField();
2952 if (!Field)
2953 return QualType();
2954
2955 QualType FT = Field->getType();
2956
2957 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2958 uint64_t BitWidth = BitWidthAP.getZExtValue();
2959 uint64_t IntSize = getTypeSize(IntTy);
2960 // GCC extension compatibility: if the bit-field size is less than or equal
2961 // to the size of int, it gets promoted no matter what its type is.
2962 // For instance, unsigned long bf : 4 gets promoted to signed int.
2963 if (BitWidth < IntSize)
2964 return IntTy;
2965
2966 if (BitWidth == IntSize)
2967 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2968
2969 // Types bigger than int are not subject to promotions, and therefore act
2970 // like the base type.
2971 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2972 // is ridiculous.
2973 return QualType();
2974}
2975
Eli Friedmana95d7572009-08-19 07:44:53 +00002976/// getPromotedIntegerType - Returns the type that Promotable will
2977/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2978/// integer type.
2979QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2980 assert(!Promotable.isNull());
2981 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002982 if (const EnumType *ET = Promotable->getAs<EnumType>())
2983 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002984 if (Promotable->isSignedIntegerType())
2985 return IntTy;
2986 uint64_t PromotableSize = getTypeSize(Promotable);
2987 uint64_t IntSize = getTypeSize(IntTy);
2988 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2989 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2990}
2991
Mike Stump1eb44332009-09-09 15:08:12 +00002992/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002993/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002994/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002995int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002996 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2997 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002998 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002999
Chris Lattnerf52ab252008-04-06 22:59:24 +00003000 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3001 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Chris Lattner7cfeb082008-04-06 23:55:33 +00003003 unsigned LHSRank = getIntegerRank(LHSC);
3004 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Chris Lattner7cfeb082008-04-06 23:55:33 +00003006 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3007 if (LHSRank == RHSRank) return 0;
3008 return LHSRank > RHSRank ? 1 : -1;
3009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Chris Lattner7cfeb082008-04-06 23:55:33 +00003011 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3012 if (LHSUnsigned) {
3013 // If the unsigned [LHS] type is larger, return it.
3014 if (LHSRank >= RHSRank)
3015 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Chris Lattner7cfeb082008-04-06 23:55:33 +00003017 // If the signed type can represent all values of the unsigned type, it
3018 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003019 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003020 return -1;
3021 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003022
Chris Lattner7cfeb082008-04-06 23:55:33 +00003023 // If the unsigned [RHS] type is larger, return it.
3024 if (RHSRank >= LHSRank)
3025 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Chris Lattner7cfeb082008-04-06 23:55:33 +00003027 // If the signed type can represent all values of the unsigned type, it
3028 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003029 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003030 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003031}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003032
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003033static RecordDecl *
3034CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3035 SourceLocation L, IdentifierInfo *Id) {
3036 if (Ctx.getLangOptions().CPlusPlus)
3037 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3038 else
3039 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3040}
3041
Mike Stump1eb44332009-09-09 15:08:12 +00003042// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003043QualType ASTContext::getCFConstantStringType() {
3044 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003045 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003046 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3047 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003048 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003049
Anders Carlssonf06273f2007-11-19 00:25:30 +00003050 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Anders Carlsson71993dd2007-08-17 05:31:46 +00003052 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003053 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003054 // int flags;
3055 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003056 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003057 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003058 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003059 FieldTypes[3] = LongTy;
3060
Anders Carlsson71993dd2007-08-17 05:31:46 +00003061 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003062 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003063 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003064 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003065 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003066 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003067 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003068 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003069 }
3070
Douglas Gregor838db382010-02-11 01:19:42 +00003071 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003072 }
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Anders Carlsson71993dd2007-08-17 05:31:46 +00003074 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003075}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003076
Douglas Gregor319ac892009-04-23 22:29:11 +00003077void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003078 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003079 assert(Rec && "Invalid CFConstantStringType");
3080 CFConstantStringTypeDecl = Rec->getDecl();
3081}
3082
Mike Stump1eb44332009-09-09 15:08:12 +00003083QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003084 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003085 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003086 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3087 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003088 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003090 QualType FieldTypes[] = {
3091 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003092 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003093 getPointerType(UnsignedLongTy),
3094 getConstantArrayType(UnsignedLongTy,
3095 llvm::APInt(32, 5), ArrayType::Normal, 0)
3096 };
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Douglas Gregor44b43212008-12-11 16:49:14 +00003098 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003099 FieldDecl *Field = FieldDecl::Create(*this,
3100 ObjCFastEnumerationStateTypeDecl,
3101 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003102 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003103 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003104 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003105 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003106 }
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Douglas Gregor838db382010-02-11 01:19:42 +00003108 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003111 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3112}
3113
Mike Stumpadaaad32009-10-20 02:12:22 +00003114QualType ASTContext::getBlockDescriptorType() {
3115 if (BlockDescriptorType)
3116 return getTagDeclType(BlockDescriptorType);
3117
3118 RecordDecl *T;
3119 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003120 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3121 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003122 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003123
3124 QualType FieldTypes[] = {
3125 UnsignedLongTy,
3126 UnsignedLongTy,
3127 };
3128
3129 const char *FieldNames[] = {
3130 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003131 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003132 };
3133
3134 for (size_t i = 0; i < 2; ++i) {
3135 FieldDecl *Field = FieldDecl::Create(*this,
3136 T,
3137 SourceLocation(),
3138 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003139 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003140 /*BitWidth=*/0,
3141 /*Mutable=*/false);
3142 T->addDecl(Field);
3143 }
3144
Douglas Gregor838db382010-02-11 01:19:42 +00003145 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003146
3147 BlockDescriptorType = T;
3148
3149 return getTagDeclType(BlockDescriptorType);
3150}
3151
3152void ASTContext::setBlockDescriptorType(QualType T) {
3153 const RecordType *Rec = T->getAs<RecordType>();
3154 assert(Rec && "Invalid BlockDescriptorType");
3155 BlockDescriptorType = Rec->getDecl();
3156}
3157
Mike Stump083c25e2009-10-22 00:49:09 +00003158QualType ASTContext::getBlockDescriptorExtendedType() {
3159 if (BlockDescriptorExtendedType)
3160 return getTagDeclType(BlockDescriptorExtendedType);
3161
3162 RecordDecl *T;
3163 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003164 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3165 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003166 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003167
3168 QualType FieldTypes[] = {
3169 UnsignedLongTy,
3170 UnsignedLongTy,
3171 getPointerType(VoidPtrTy),
3172 getPointerType(VoidPtrTy)
3173 };
3174
3175 const char *FieldNames[] = {
3176 "reserved",
3177 "Size",
3178 "CopyFuncPtr",
3179 "DestroyFuncPtr"
3180 };
3181
3182 for (size_t i = 0; i < 4; ++i) {
3183 FieldDecl *Field = FieldDecl::Create(*this,
3184 T,
3185 SourceLocation(),
3186 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003187 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003188 /*BitWidth=*/0,
3189 /*Mutable=*/false);
3190 T->addDecl(Field);
3191 }
3192
Douglas Gregor838db382010-02-11 01:19:42 +00003193 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003194
3195 BlockDescriptorExtendedType = T;
3196
3197 return getTagDeclType(BlockDescriptorExtendedType);
3198}
3199
3200void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3201 const RecordType *Rec = T->getAs<RecordType>();
3202 assert(Rec && "Invalid BlockDescriptorType");
3203 BlockDescriptorExtendedType = Rec->getDecl();
3204}
3205
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003206bool ASTContext::BlockRequiresCopying(QualType Ty) {
3207 if (Ty->isBlockPointerType())
3208 return true;
3209 if (isObjCNSObjectType(Ty))
3210 return true;
3211 if (Ty->isObjCObjectPointerType())
3212 return true;
3213 return false;
3214}
3215
3216QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3217 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003218 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003219 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003220 // unsigned int __flags;
3221 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003222 // void *__copy_helper; // as needed
3223 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003224 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003225 // } *
3226
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003227 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3228
3229 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003230 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003231 llvm::SmallString<36> Name;
3232 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3233 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003234 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003235 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3236 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003237 T->startDefinition();
3238 QualType Int32Ty = IntTy;
3239 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3240 QualType FieldTypes[] = {
3241 getPointerType(VoidPtrTy),
3242 getPointerType(getTagDeclType(T)),
3243 Int32Ty,
3244 Int32Ty,
3245 getPointerType(VoidPtrTy),
3246 getPointerType(VoidPtrTy),
3247 Ty
3248 };
3249
3250 const char *FieldNames[] = {
3251 "__isa",
3252 "__forwarding",
3253 "__flags",
3254 "__size",
3255 "__copy_helper",
3256 "__destroy_helper",
3257 DeclName,
3258 };
3259
3260 for (size_t i = 0; i < 7; ++i) {
3261 if (!HasCopyAndDispose && i >=4 && i <= 5)
3262 continue;
3263 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3264 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003265 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003266 /*BitWidth=*/0, /*Mutable=*/false);
3267 T->addDecl(Field);
3268 }
3269
Douglas Gregor838db382010-02-11 01:19:42 +00003270 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003271
3272 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003273}
3274
3275
3276QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003277 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003278 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003279 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003280 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003281 llvm::SmallString<36> Name;
3282 llvm::raw_svector_ostream(Name) << "__block_literal_"
3283 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003284 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003285 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3286 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003287 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003288 QualType FieldTypes[] = {
3289 getPointerType(VoidPtrTy),
3290 IntTy,
3291 IntTy,
3292 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003293 (BlockHasCopyDispose ?
3294 getPointerType(getBlockDescriptorExtendedType()) :
3295 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003296 };
3297
3298 const char *FieldNames[] = {
3299 "__isa",
3300 "__flags",
3301 "__reserved",
3302 "__FuncPtr",
3303 "__descriptor"
3304 };
3305
3306 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003307 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003308 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003309 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003310 /*BitWidth=*/0, /*Mutable=*/false);
3311 T->addDecl(Field);
3312 }
3313
3314 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3315 const Expr *E = BlockDeclRefDecls[i];
3316 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3317 clang::IdentifierInfo *Name = 0;
3318 if (BDRE) {
3319 const ValueDecl *D = BDRE->getDecl();
3320 Name = &Idents.get(D->getName());
3321 }
3322 QualType FieldType = E->getType();
3323
3324 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003325 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3326 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003327
3328 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003329 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003330 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003331 T->addDecl(Field);
3332 }
3333
Douglas Gregor838db382010-02-11 01:19:42 +00003334 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003335
3336 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003337}
3338
Douglas Gregor319ac892009-04-23 22:29:11 +00003339void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003340 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003341 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3342 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3343}
3344
Anders Carlssone8c49532007-10-29 06:33:42 +00003345// This returns true if a type has been typedefed to BOOL:
3346// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003347static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003348 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003349 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3350 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003352 return false;
3353}
3354
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003355/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003356/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003357CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003358 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003360 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003361 if (sz.isPositive() && type->isIntegralType())
3362 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003363 // Treat arrays as pointers, since that's how they're passed in.
3364 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003365 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003366 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003367}
3368
3369static inline
3370std::string charUnitsToString(const CharUnits &CU) {
3371 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003372}
3373
David Chisnall5e530af2009-11-17 19:33:30 +00003374/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3375/// declaration.
3376void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3377 std::string& S) {
3378 const BlockDecl *Decl = Expr->getBlockDecl();
3379 QualType BlockTy =
3380 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3381 // Encode result type.
3382 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3383 // Compute size of all parameters.
3384 // Start with computing size of a pointer in number of bytes.
3385 // FIXME: There might(should) be a better way of doing this computation!
3386 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003387 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3388 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003389 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3390 E = Decl->param_end(); PI != E; ++PI) {
3391 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003392 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003393 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003394 ParmOffset += sz;
3395 }
3396 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003397 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003398 // Block pointer and offset.
3399 S += "@?0";
3400 ParmOffset = PtrSize;
3401
3402 // Argument types.
3403 ParmOffset = PtrSize;
3404 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3405 Decl->param_end(); PI != E; ++PI) {
3406 ParmVarDecl *PVDecl = *PI;
3407 QualType PType = PVDecl->getOriginalType();
3408 if (const ArrayType *AT =
3409 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3410 // Use array's original type only if it has known number of
3411 // elements.
3412 if (!isa<ConstantArrayType>(AT))
3413 PType = PVDecl->getType();
3414 } else if (PType->isFunctionType())
3415 PType = PVDecl->getType();
3416 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003417 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003418 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003419 }
3420}
3421
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003422/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003423/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003424void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003425 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003426 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003427 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003428 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003429 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003430 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003431 // Compute size of all parameters.
3432 // Start with computing size of a pointer in number of bytes.
3433 // FIXME: There might(should) be a better way of doing this computation!
3434 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003435 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003436 // The first two arguments (self and _cmd) are pointers; account for
3437 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003438 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003439 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3440 E = Decl->param_end(); PI != E; ++PI) {
3441 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003442 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003443 assert (sz.isPositive() &&
3444 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003445 ParmOffset += sz;
3446 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003447 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003448 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003449 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003451 // Argument types.
3452 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003453 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3454 E = Decl->param_end(); PI != E; ++PI) {
3455 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003456 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003457 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003458 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3459 // Use array's original type only if it has known number of
3460 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003461 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003462 PType = PVDecl->getType();
3463 } else if (PType->isFunctionType())
3464 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003465 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003466 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003467 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003468 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003469 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003470 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003471 }
3472}
3473
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003474/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003475/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003476/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3477/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003478/// Property attributes are stored as a comma-delimited C string. The simple
3479/// attributes readonly and bycopy are encoded as single characters. The
3480/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3481/// encoded as single characters, followed by an identifier. Property types
3482/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003483/// these attributes are defined by the following enumeration:
3484/// @code
3485/// enum PropertyAttributes {
3486/// kPropertyReadOnly = 'R', // property is read-only.
3487/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3488/// kPropertyByref = '&', // property is a reference to the value last assigned
3489/// kPropertyDynamic = 'D', // property is dynamic
3490/// kPropertyGetter = 'G', // followed by getter selector name
3491/// kPropertySetter = 'S', // followed by setter selector name
3492/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3493/// kPropertyType = 't' // followed by old-style type encoding.
3494/// kPropertyWeak = 'W' // 'weak' property
3495/// kPropertyStrong = 'P' // property GC'able
3496/// kPropertyNonAtomic = 'N' // property non-atomic
3497/// };
3498/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003499void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003500 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003501 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003502 // Collect information from the property implementation decl(s).
3503 bool Dynamic = false;
3504 ObjCPropertyImplDecl *SynthesizePID = 0;
3505
3506 // FIXME: Duplicated code due to poor abstraction.
3507 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003508 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003509 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3510 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003511 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003512 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003513 ObjCPropertyImplDecl *PID = *i;
3514 if (PID->getPropertyDecl() == PD) {
3515 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3516 Dynamic = true;
3517 } else {
3518 SynthesizePID = PID;
3519 }
3520 }
3521 }
3522 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003523 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003524 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003525 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003526 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003527 ObjCPropertyImplDecl *PID = *i;
3528 if (PID->getPropertyDecl() == PD) {
3529 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3530 Dynamic = true;
3531 } else {
3532 SynthesizePID = PID;
3533 }
3534 }
Mike Stump1eb44332009-09-09 15:08:12 +00003535 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003536 }
3537 }
3538
3539 // FIXME: This is not very efficient.
3540 S = "T";
3541
3542 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003543 // GCC has some special rules regarding encoding of properties which
3544 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003545 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003546 true /* outermost type */,
3547 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003548
3549 if (PD->isReadOnly()) {
3550 S += ",R";
3551 } else {
3552 switch (PD->getSetterKind()) {
3553 case ObjCPropertyDecl::Assign: break;
3554 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003555 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003556 }
3557 }
3558
3559 // It really isn't clear at all what this means, since properties
3560 // are "dynamic by default".
3561 if (Dynamic)
3562 S += ",D";
3563
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003564 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3565 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003567 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3568 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003569 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003570 }
3571
3572 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3573 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003574 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003575 }
3576
3577 if (SynthesizePID) {
3578 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3579 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003580 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003581 }
3582
3583 // FIXME: OBJCGC: weak & strong
3584}
3585
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003586/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003587/// Another legacy compatibility encoding: 32-bit longs are encoded as
3588/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003589/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3590///
3591void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003592 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003593 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003594 if (BT->getKind() == BuiltinType::ULong &&
3595 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003596 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003597 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003598 if (BT->getKind() == BuiltinType::Long &&
3599 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003600 PointeeTy = IntTy;
3601 }
3602 }
3603}
3604
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003605void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003606 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003607 // We follow the behavior of gcc, expanding structures which are
3608 // directly pointed to, and expanding embedded structures. Note that
3609 // these rules are sufficient to prevent recursive encoding of the
3610 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003611 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003612 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003613}
3614
Mike Stump1eb44332009-09-09 15:08:12 +00003615static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003616 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003617 const Expr *E = FD->getBitWidth();
3618 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3619 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003620 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003621 S += 'b';
3622 S += llvm::utostr(N);
3623}
3624
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003625// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003626void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3627 bool ExpandPointedToStructures,
3628 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003629 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003630 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003631 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003632 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003633 if (FD && FD->isBitField())
3634 return EncodeBitField(this, S, FD);
3635 char encoding;
3636 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003637 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003638 case BuiltinType::Void: encoding = 'v'; break;
3639 case BuiltinType::Bool: encoding = 'B'; break;
3640 case BuiltinType::Char_U:
3641 case BuiltinType::UChar: encoding = 'C'; break;
3642 case BuiltinType::UShort: encoding = 'S'; break;
3643 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003644 case BuiltinType::ULong:
3645 encoding =
3646 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003647 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003648 case BuiltinType::UInt128: encoding = 'T'; break;
3649 case BuiltinType::ULongLong: encoding = 'Q'; break;
3650 case BuiltinType::Char_S:
3651 case BuiltinType::SChar: encoding = 'c'; break;
3652 case BuiltinType::Short: encoding = 's'; break;
3653 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003654 case BuiltinType::Long:
3655 encoding =
3656 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003657 break;
3658 case BuiltinType::LongLong: encoding = 'q'; break;
3659 case BuiltinType::Int128: encoding = 't'; break;
3660 case BuiltinType::Float: encoding = 'f'; break;
3661 case BuiltinType::Double: encoding = 'd'; break;
3662 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003663 }
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003665 S += encoding;
3666 return;
3667 }
Mike Stump1eb44332009-09-09 15:08:12 +00003668
John McCall183700f2009-09-21 23:43:11 +00003669 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003670 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003671 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003672 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003673 return;
3674 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003675
Ted Kremenek6217b802009-07-29 21:53:49 +00003676 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003677 if (PT->isObjCSelType()) {
3678 S += ':';
3679 return;
3680 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003681 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003682
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003683 bool isReadOnly = false;
3684 // For historical/compatibility reasons, the read-only qualifier of the
3685 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3686 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003687 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003688 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003689 if (OutermostType && T.isConstQualified()) {
3690 isReadOnly = true;
3691 S += 'r';
3692 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003693 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003694 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003695 while (P->getAs<PointerType>())
3696 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003697 if (P.isConstQualified()) {
3698 isReadOnly = true;
3699 S += 'r';
3700 }
3701 }
3702 if (isReadOnly) {
3703 // Another legacy compatibility encoding. Some ObjC qualifier and type
3704 // combinations need to be rearranged.
3705 // Rewrite "in const" from "nr" to "rn"
3706 const char * s = S.c_str();
3707 int len = S.length();
3708 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3709 std::string replace = "rn";
3710 S.replace(S.end()-2, S.end(), replace);
3711 }
3712 }
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003714 if (PointeeTy->isCharType()) {
3715 // char pointer types should be encoded as '*' unless it is a
3716 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003717 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003718 S += '*';
3719 return;
3720 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003721 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003722 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3723 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3724 S += '#';
3725 return;
3726 }
3727 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3728 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3729 S += '@';
3730 return;
3731 }
3732 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003733 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003734 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003735 getLegacyIntegralTypeEncoding(PointeeTy);
3736
Mike Stump1eb44332009-09-09 15:08:12 +00003737 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003738 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003739 return;
3740 }
Mike Stump1eb44332009-09-09 15:08:12 +00003741
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003742 if (const ArrayType *AT =
3743 // Ignore type qualifiers etc.
3744 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003745 if (isa<IncompleteArrayType>(AT)) {
3746 // Incomplete arrays are encoded as a pointer to the array element.
3747 S += '^';
3748
Mike Stump1eb44332009-09-09 15:08:12 +00003749 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003750 false, ExpandStructures, FD);
3751 } else {
3752 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003753
Anders Carlsson559a8332009-02-22 01:38:57 +00003754 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3755 S += llvm::utostr(CAT->getSize().getZExtValue());
3756 else {
3757 //Variable length arrays are encoded as a regular array with 0 elements.
3758 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3759 S += '0';
3760 }
Mike Stump1eb44332009-09-09 15:08:12 +00003761
3762 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003763 false, ExpandStructures, FD);
3764 S += ']';
3765 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003766 return;
3767 }
Mike Stump1eb44332009-09-09 15:08:12 +00003768
John McCall183700f2009-09-21 23:43:11 +00003769 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003770 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003771 return;
3772 }
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Ted Kremenek6217b802009-07-29 21:53:49 +00003774 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003775 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003776 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003777 // Anonymous structures print as '?'
3778 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3779 S += II->getName();
3780 } else {
3781 S += '?';
3782 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003783 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003784 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003785 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3786 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003787 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003788 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003789 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003790 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003791 S += '"';
3792 }
Mike Stump1eb44332009-09-09 15:08:12 +00003793
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003794 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003795 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003796 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003797 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003798 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003799 QualType qt = Field->getType();
3800 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003801 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003802 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003803 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003804 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003805 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003806 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003807 return;
3808 }
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003810 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003811 if (FD && FD->isBitField())
3812 EncodeBitField(this, S, FD);
3813 else
3814 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003815 return;
3816 }
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003818 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003819 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003820 return;
3821 }
Mike Stump1eb44332009-09-09 15:08:12 +00003822
John McCall0953e762009-09-24 19:53:00 +00003823 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003824 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003825 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003826 S += '{';
3827 const IdentifierInfo *II = OI->getIdentifier();
3828 S += II->getName();
3829 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003830 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003831 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003832 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003833 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003834 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003835 RecFields[i]);
3836 else
Mike Stump1eb44332009-09-09 15:08:12 +00003837 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003838 FD);
3839 }
3840 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003841 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003842 }
Mike Stump1eb44332009-09-09 15:08:12 +00003843
John McCall183700f2009-09-21 23:43:11 +00003844 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003845 if (OPT->isObjCIdType()) {
3846 S += '@';
3847 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Steve Naroff27d20a22009-10-28 22:03:49 +00003850 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3851 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3852 // Since this is a binary compatibility issue, need to consult with runtime
3853 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003854 S += '#';
3855 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003858 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003859 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003860 ExpandPointedToStructures,
3861 ExpandStructures, FD);
3862 if (FD || EncodingProperty) {
3863 // Note that we do extended encoding of protocol qualifer list
3864 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003865 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003866 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3867 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003868 S += '<';
3869 S += (*I)->getNameAsString();
3870 S += '>';
3871 }
3872 S += '"';
3873 }
3874 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003875 }
Mike Stump1eb44332009-09-09 15:08:12 +00003876
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003877 QualType PointeeTy = OPT->getPointeeType();
3878 if (!EncodingProperty &&
3879 isa<TypedefType>(PointeeTy.getTypePtr())) {
3880 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003881 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003882 // {...};
3883 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003884 getObjCEncodingForTypeImpl(PointeeTy, S,
3885 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003886 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003887 return;
3888 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003889
3890 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003891 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003892 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003893 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003894 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3895 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003896 S += '<';
3897 S += (*I)->getNameAsString();
3898 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003899 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003900 S += '"';
3901 }
3902 return;
3903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003905 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003906}
3907
Mike Stump1eb44332009-09-09 15:08:12 +00003908void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003909 std::string& S) const {
3910 if (QT & Decl::OBJC_TQ_In)
3911 S += 'n';
3912 if (QT & Decl::OBJC_TQ_Inout)
3913 S += 'N';
3914 if (QT & Decl::OBJC_TQ_Out)
3915 S += 'o';
3916 if (QT & Decl::OBJC_TQ_Bycopy)
3917 S += 'O';
3918 if (QT & Decl::OBJC_TQ_Byref)
3919 S += 'R';
3920 if (QT & Decl::OBJC_TQ_Oneway)
3921 S += 'V';
3922}
3923
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003924void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003925 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003927 BuiltinVaListType = T;
3928}
3929
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003930void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003931 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003932}
3933
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003934void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003935 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003936}
3937
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003938void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003939 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003940}
3941
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003942void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003943 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003944}
3945
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003946void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003947 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003948 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003950 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003951}
3952
John McCall0bd6feb2009-12-02 08:04:21 +00003953/// \brief Retrieve the template name that corresponds to a non-empty
3954/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003955TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3956 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003957 unsigned size = End - Begin;
3958 assert(size > 1 && "set is not overloaded!");
3959
3960 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3961 size * sizeof(FunctionTemplateDecl*));
3962 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3963
3964 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003965 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003966 NamedDecl *D = *I;
3967 assert(isa<FunctionTemplateDecl>(D) ||
3968 (isa<UsingShadowDecl>(D) &&
3969 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3970 *Storage++ = D;
3971 }
3972
3973 return TemplateName(OT);
3974}
3975
Douglas Gregor7532dc62009-03-30 22:58:21 +00003976/// \brief Retrieve the template name that represents a qualified
3977/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003978TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003979 bool TemplateKeyword,
3980 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003981 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003982 llvm::FoldingSetNodeID ID;
3983 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3984
3985 void *InsertPos = 0;
3986 QualifiedTemplateName *QTN =
3987 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3988 if (!QTN) {
3989 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3990 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3991 }
3992
3993 return TemplateName(QTN);
3994}
3995
3996/// \brief Retrieve the template name that represents a dependent
3997/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003998TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003999 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004000 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004001 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004002
4003 llvm::FoldingSetNodeID ID;
4004 DependentTemplateName::Profile(ID, NNS, Name);
4005
4006 void *InsertPos = 0;
4007 DependentTemplateName *QTN =
4008 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4009
4010 if (QTN)
4011 return TemplateName(QTN);
4012
4013 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4014 if (CanonNNS == NNS) {
4015 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4016 } else {
4017 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4018 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004019 DependentTemplateName *CheckQTN =
4020 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4021 assert(!CheckQTN && "Dependent type name canonicalization broken");
4022 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004023 }
4024
4025 DependentTemplateNames.InsertNode(QTN, InsertPos);
4026 return TemplateName(QTN);
4027}
4028
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004029/// \brief Retrieve the template name that represents a dependent
4030/// template name such as \c MetaFun::template operator+.
4031TemplateName
4032ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4033 OverloadedOperatorKind Operator) {
4034 assert((!NNS || NNS->isDependent()) &&
4035 "Nested name specifier must be dependent");
4036
4037 llvm::FoldingSetNodeID ID;
4038 DependentTemplateName::Profile(ID, NNS, Operator);
4039
4040 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004041 DependentTemplateName *QTN
4042 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004043
4044 if (QTN)
4045 return TemplateName(QTN);
4046
4047 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4048 if (CanonNNS == NNS) {
4049 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4050 } else {
4051 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4052 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004053
4054 DependentTemplateName *CheckQTN
4055 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4056 assert(!CheckQTN && "Dependent template name canonicalization broken");
4057 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004058 }
4059
4060 DependentTemplateNames.InsertNode(QTN, InsertPos);
4061 return TemplateName(QTN);
4062}
4063
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004064/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004065/// TargetInfo, produce the corresponding type. The unsigned @p Type
4066/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004067CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004068 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004069 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004070 case TargetInfo::SignedShort: return ShortTy;
4071 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4072 case TargetInfo::SignedInt: return IntTy;
4073 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4074 case TargetInfo::SignedLong: return LongTy;
4075 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4076 case TargetInfo::SignedLongLong: return LongLongTy;
4077 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4078 }
4079
4080 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004081 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004082}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004083
4084//===----------------------------------------------------------------------===//
4085// Type Predicates.
4086//===----------------------------------------------------------------------===//
4087
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004088/// isObjCNSObjectType - Return true if this is an NSObject object using
4089/// NSObject attribute on a c-style pointer type.
4090/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004091/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004092///
4093bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4094 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4095 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004096 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004097 return true;
4098 }
Mike Stump1eb44332009-09-09 15:08:12 +00004099 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004100}
4101
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004102/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4103/// garbage collection attribute.
4104///
John McCall0953e762009-09-24 19:53:00 +00004105Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4106 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004107 if (getLangOptions().ObjC1 &&
4108 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004109 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004110 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004111 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004112 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004113 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004114 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004115 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004116 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004117 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004118 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004119 // Non-pointers have none gc'able attribute regardless of the attribute
4120 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004121 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004122 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004123 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004124 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004125}
4126
Chris Lattner6ac46a42008-04-07 06:51:04 +00004127//===----------------------------------------------------------------------===//
4128// Type Compatibility Testing
4129//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004130
Mike Stump1eb44332009-09-09 15:08:12 +00004131/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004132/// compatible.
4133static bool areCompatVectorTypes(const VectorType *LHS,
4134 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004135 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004136 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004137 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004138}
4139
Steve Naroff4084c302009-07-23 01:01:38 +00004140//===----------------------------------------------------------------------===//
4141// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4142//===----------------------------------------------------------------------===//
4143
4144/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4145/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004146bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4147 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004148 if (lProto == rProto)
4149 return true;
4150 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4151 E = rProto->protocol_end(); PI != E; ++PI)
4152 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4153 return true;
4154 return false;
4155}
4156
Steve Naroff4084c302009-07-23 01:01:38 +00004157/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4158/// return true if lhs's protocols conform to rhs's protocol; false
4159/// otherwise.
4160bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4161 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4162 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4163 return false;
4164}
4165
4166/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4167/// ObjCQualifiedIDType.
4168bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4169 bool compare) {
4170 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004171 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004172 lhs->isObjCIdType() || lhs->isObjCClassType())
4173 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004174 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004175 rhs->isObjCIdType() || rhs->isObjCClassType())
4176 return true;
4177
4178 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004179 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Steve Naroff4084c302009-07-23 01:01:38 +00004181 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Steve Naroff4084c302009-07-23 01:01:38 +00004183 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004184 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004185 // make sure we check the class hierarchy.
4186 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4187 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4188 E = lhsQID->qual_end(); I != E; ++I) {
4189 // when comparing an id<P> on lhs with a static type on rhs,
4190 // see if static class implements all of id's protocols, directly or
4191 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004192 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004193 return false;
4194 }
4195 }
4196 // If there are no qualifiers and no interface, we have an 'id'.
4197 return true;
4198 }
Mike Stump1eb44332009-09-09 15:08:12 +00004199 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004200 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4201 E = lhsQID->qual_end(); I != E; ++I) {
4202 ObjCProtocolDecl *lhsProto = *I;
4203 bool match = false;
4204
4205 // when comparing an id<P> on lhs with a static type on rhs,
4206 // see if static class implements all of id's protocols, directly or
4207 // through its super class and categories.
4208 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4209 E = rhsOPT->qual_end(); J != E; ++J) {
4210 ObjCProtocolDecl *rhsProto = *J;
4211 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4212 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4213 match = true;
4214 break;
4215 }
4216 }
Mike Stump1eb44332009-09-09 15:08:12 +00004217 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004218 // make sure we check the class hierarchy.
4219 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4220 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4221 E = lhsQID->qual_end(); I != E; ++I) {
4222 // when comparing an id<P> on lhs with a static type on rhs,
4223 // see if static class implements all of id's protocols, directly or
4224 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004225 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004226 match = true;
4227 break;
4228 }
4229 }
4230 }
4231 if (!match)
4232 return false;
4233 }
Mike Stump1eb44332009-09-09 15:08:12 +00004234
Steve Naroff4084c302009-07-23 01:01:38 +00004235 return true;
4236 }
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Steve Naroff4084c302009-07-23 01:01:38 +00004238 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4239 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4240
Mike Stump1eb44332009-09-09 15:08:12 +00004241 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004242 lhs->getAsObjCInterfacePointerType()) {
4243 if (lhsOPT->qual_empty()) {
4244 bool match = false;
4245 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4246 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4247 E = rhsQID->qual_end(); I != E; ++I) {
4248 // when comparing an id<P> on lhs with a static type on rhs,
4249 // see if static class implements all of id's protocols, directly or
4250 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004251 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004252 match = true;
4253 break;
4254 }
4255 }
4256 if (!match)
4257 return false;
4258 }
4259 return true;
4260 }
Mike Stump1eb44332009-09-09 15:08:12 +00004261 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004262 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4263 E = lhsOPT->qual_end(); I != E; ++I) {
4264 ObjCProtocolDecl *lhsProto = *I;
4265 bool match = false;
4266
4267 // when comparing an id<P> on lhs with a static type on rhs,
4268 // see if static class implements all of id's protocols, directly or
4269 // through its super class and categories.
4270 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4271 E = rhsQID->qual_end(); J != E; ++J) {
4272 ObjCProtocolDecl *rhsProto = *J;
4273 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4274 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4275 match = true;
4276 break;
4277 }
4278 }
4279 if (!match)
4280 return false;
4281 }
4282 return true;
4283 }
4284 return false;
4285}
4286
Eli Friedman3d815e72008-08-22 00:56:42 +00004287/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004288/// compatible for assignment from RHS to LHS. This handles validation of any
4289/// protocol qualifiers on the LHS or RHS.
4290///
Steve Naroff14108da2009-07-10 23:34:53 +00004291bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4292 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004293 // If either type represents the built-in 'id' or 'Class' types, return true.
4294 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004295 return true;
4296
Steve Naroff4084c302009-07-23 01:01:38 +00004297 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004298 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4299 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004300 false);
4301
Steve Naroff14108da2009-07-10 23:34:53 +00004302 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4303 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004304 if (LHS && RHS) // We have 2 user-defined types.
4305 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Steve Naroff4084c302009-07-23 01:01:38 +00004307 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004308}
4309
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004310/// getIntersectionOfProtocols - This routine finds the intersection of set
4311/// of protocols inherited from two distinct objective-c pointer objects.
4312/// It is used to build composite qualifier list of the composite type of
4313/// the conditional expression involving two objective-c pointer objects.
4314static
4315void getIntersectionOfProtocols(ASTContext &Context,
4316 const ObjCObjectPointerType *LHSOPT,
4317 const ObjCObjectPointerType *RHSOPT,
4318 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4319
4320 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4321 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4322
4323 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4324 unsigned LHSNumProtocols = LHS->getNumProtocols();
4325 if (LHSNumProtocols > 0)
4326 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4327 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004328 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4329 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004330 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4331 LHSInheritedProtocols.end());
4332 }
4333
4334 unsigned RHSNumProtocols = RHS->getNumProtocols();
4335 if (RHSNumProtocols > 0) {
4336 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4337 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4338 if (InheritedProtocolSet.count(RHSProtocols[i]))
4339 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4340 }
4341 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004342 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004343 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004344 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4345 RHSInheritedProtocols.begin(),
4346 E = RHSInheritedProtocols.end(); I != E; ++I)
4347 if (InheritedProtocolSet.count((*I)))
4348 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004349 }
4350}
4351
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004352/// areCommonBaseCompatible - Returns common base class of the two classes if
4353/// one found. Note that this is O'2 algorithm. But it will be called as the
4354/// last type comparison in a ?-exp of ObjC pointer types before a
4355/// warning is issued. So, its invokation is extremely rare.
4356QualType ASTContext::areCommonBaseCompatible(
4357 const ObjCObjectPointerType *LHSOPT,
4358 const ObjCObjectPointerType *RHSOPT) {
4359 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4360 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4361 if (!LHS || !RHS)
4362 return QualType();
4363
4364 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4365 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4366 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004367 if (canAssignObjCInterfaces(LHS, RHS)) {
4368 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4369 getIntersectionOfProtocols(*this,
4370 LHSOPT, RHSOPT, IntersectionOfProtocols);
4371 if (IntersectionOfProtocols.empty())
4372 LHSTy = getObjCObjectPointerType(LHSTy);
4373 else
4374 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4375 IntersectionOfProtocols.size());
4376 return LHSTy;
4377 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004378 }
4379
4380 return QualType();
4381}
4382
Eli Friedman3d815e72008-08-22 00:56:42 +00004383bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4384 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004385 // Verify that the base decls are compatible: the RHS must be a subclass of
4386 // the LHS.
4387 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4388 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Chris Lattner6ac46a42008-04-07 06:51:04 +00004390 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4391 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004392 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004393 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Chris Lattner6ac46a42008-04-07 06:51:04 +00004395 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4396 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004397 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004398 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004399
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004400 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4401 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004402 LHSPI != LHSPE; LHSPI++) {
4403 bool RHSImplementsProtocol = false;
4404
4405 // If the RHS doesn't implement the protocol on the left, the types
4406 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004407 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004408 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004409 RHSPI != RHSPE; RHSPI++) {
4410 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004411 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004412 break;
4413 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004414 }
4415 // FIXME: For better diagnostics, consider passing back the protocol name.
4416 if (!RHSImplementsProtocol)
4417 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004418 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004419 // The RHS implements all protocols listed on the LHS.
4420 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004421}
4422
Steve Naroff389bf462009-02-12 17:52:19 +00004423bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4424 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004425 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4426 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Steve Naroff14108da2009-07-10 23:34:53 +00004428 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004429 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004430
4431 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4432 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004433}
4434
Mike Stump1eb44332009-09-09 15:08:12 +00004435/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004436/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004437/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004438/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004439bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004440 if (getLangOptions().CPlusPlus)
4441 return hasSameType(LHS, RHS);
4442
Eli Friedman3d815e72008-08-22 00:56:42 +00004443 return !mergeTypes(LHS, RHS).isNull();
4444}
4445
4446QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004447 const FunctionType *lbase = lhs->getAs<FunctionType>();
4448 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004449 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4450 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004451 bool allLTypes = true;
4452 bool allRTypes = true;
4453
4454 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004455 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004456 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004457 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004458 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004459 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004460 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004461 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004462 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4463 if (NoReturn != lbase->getNoReturnAttr())
4464 allLTypes = false;
4465 if (NoReturn != rbase->getNoReturnAttr())
4466 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004467 CallingConv lcc = lbase->getCallConv();
4468 CallingConv rcc = rbase->getCallConv();
4469 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004470 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004471 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004472
Eli Friedman3d815e72008-08-22 00:56:42 +00004473 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004474 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4475 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004476 unsigned lproto_nargs = lproto->getNumArgs();
4477 unsigned rproto_nargs = rproto->getNumArgs();
4478
4479 // Compatible functions must have the same number of arguments
4480 if (lproto_nargs != rproto_nargs)
4481 return QualType();
4482
4483 // Variadic and non-variadic functions aren't compatible
4484 if (lproto->isVariadic() != rproto->isVariadic())
4485 return QualType();
4486
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004487 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4488 return QualType();
4489
Eli Friedman3d815e72008-08-22 00:56:42 +00004490 // Check argument compatibility
4491 llvm::SmallVector<QualType, 10> types;
4492 for (unsigned i = 0; i < lproto_nargs; i++) {
4493 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4494 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4495 QualType argtype = mergeTypes(largtype, rargtype);
4496 if (argtype.isNull()) return QualType();
4497 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004498 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4499 allLTypes = false;
4500 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4501 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004502 }
4503 if (allLTypes) return lhs;
4504 if (allRTypes) return rhs;
4505 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004506 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004507 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004508 }
4509
4510 if (lproto) allRTypes = false;
4511 if (rproto) allLTypes = false;
4512
Douglas Gregor72564e72009-02-26 23:50:07 +00004513 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004514 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004515 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004516 if (proto->isVariadic()) return QualType();
4517 // Check that the types are compatible with the types that
4518 // would result from default argument promotions (C99 6.7.5.3p15).
4519 // The only types actually affected are promotable integer
4520 // types and floats, which would be passed as a different
4521 // type depending on whether the prototype is visible.
4522 unsigned proto_nargs = proto->getNumArgs();
4523 for (unsigned i = 0; i < proto_nargs; ++i) {
4524 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004525
4526 // Look at the promotion type of enum types, since that is the type used
4527 // to pass enum values.
4528 if (const EnumType *Enum = argTy->getAs<EnumType>())
4529 argTy = Enum->getDecl()->getPromotionType();
4530
Eli Friedman3d815e72008-08-22 00:56:42 +00004531 if (argTy->isPromotableIntegerType() ||
4532 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4533 return QualType();
4534 }
4535
4536 if (allLTypes) return lhs;
4537 if (allRTypes) return rhs;
4538 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004539 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004540 proto->getTypeQuals(),
4541 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004542 }
4543
4544 if (allLTypes) return lhs;
4545 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004546 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004547}
4548
4549QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004550 // C++ [expr]: If an expression initially has the type "reference to T", the
4551 // type is adjusted to "T" prior to any further analysis, the expression
4552 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004553 // expression is an lvalue unless the reference is an rvalue reference and
4554 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004555 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4556 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4557
Eli Friedman3d815e72008-08-22 00:56:42 +00004558 QualType LHSCan = getCanonicalType(LHS),
4559 RHSCan = getCanonicalType(RHS);
4560
4561 // If two types are identical, they are compatible.
4562 if (LHSCan == RHSCan)
4563 return LHS;
4564
John McCall0953e762009-09-24 19:53:00 +00004565 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004566 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4567 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004568 if (LQuals != RQuals) {
4569 // If any of these qualifiers are different, we have a type
4570 // mismatch.
4571 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4572 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4573 return QualType();
4574
4575 // Exactly one GC qualifier difference is allowed: __strong is
4576 // okay if the other type has no GC qualifier but is an Objective
4577 // C object pointer (i.e. implicitly strong by default). We fix
4578 // this by pretending that the unqualified type was actually
4579 // qualified __strong.
4580 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4581 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4582 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4583
4584 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4585 return QualType();
4586
4587 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4588 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4589 }
4590 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4591 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4592 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004593 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004594 }
4595
4596 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004597
Eli Friedman852d63b2009-06-01 01:22:52 +00004598 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4599 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004600
Chris Lattner1adb8832008-01-14 05:45:46 +00004601 // We want to consider the two function types to be the same for these
4602 // comparisons, just force one to the other.
4603 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4604 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004605
4606 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004607 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4608 LHSClass = Type::ConstantArray;
4609 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4610 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004611
Nate Begeman213541a2008-04-18 23:10:10 +00004612 // Canonicalize ExtVector -> Vector.
4613 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4614 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Chris Lattnera36a61f2008-04-07 05:43:21 +00004616 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004617 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004618 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004619 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004620 // Compatibility is based on the underlying type, not the promotion
4621 // type.
John McCall183700f2009-09-21 23:43:11 +00004622 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004623 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4624 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004625 }
John McCall183700f2009-09-21 23:43:11 +00004626 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004627 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4628 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004629 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004630
Eli Friedman3d815e72008-08-22 00:56:42 +00004631 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004632 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004633
Steve Naroff4a746782008-01-09 22:43:08 +00004634 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004635 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004636#define TYPE(Class, Base)
4637#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004638#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004639#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4640#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4641#include "clang/AST/TypeNodes.def"
4642 assert(false && "Non-canonical and dependent types shouldn't get here");
4643 return QualType();
4644
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004645 case Type::LValueReference:
4646 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004647 case Type::MemberPointer:
4648 assert(false && "C++ should never be in mergeTypes");
4649 return QualType();
4650
4651 case Type::IncompleteArray:
4652 case Type::VariableArray:
4653 case Type::FunctionProto:
4654 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004655 assert(false && "Types are eliminated above");
4656 return QualType();
4657
Chris Lattner1adb8832008-01-14 05:45:46 +00004658 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004659 {
4660 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004661 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4662 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004663 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4664 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004665 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004666 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004667 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004668 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004669 return getPointerType(ResultType);
4670 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004671 case Type::BlockPointer:
4672 {
4673 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004674 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4675 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004676 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4677 if (ResultType.isNull()) return QualType();
4678 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4679 return LHS;
4680 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4681 return RHS;
4682 return getBlockPointerType(ResultType);
4683 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004684 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004685 {
4686 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4687 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4688 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4689 return QualType();
4690
4691 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4692 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4693 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4694 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004695 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4696 return LHS;
4697 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4698 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004699 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4700 ArrayType::ArraySizeModifier(), 0);
4701 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4702 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004703 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4704 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004705 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4706 return LHS;
4707 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4708 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004709 if (LVAT) {
4710 // FIXME: This isn't correct! But tricky to implement because
4711 // the array's size has to be the size of LHS, but the type
4712 // has to be different.
4713 return LHS;
4714 }
4715 if (RVAT) {
4716 // FIXME: This isn't correct! But tricky to implement because
4717 // the array's size has to be the size of RHS, but the type
4718 // has to be different.
4719 return RHS;
4720 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004721 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4722 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004723 return getIncompleteArrayType(ResultType,
4724 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004725 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004726 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004727 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004728 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004729 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004730 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004731 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004732 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004733 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004734 case Type::Complex:
4735 // Distinct complex types are incompatible.
4736 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004737 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004738 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004739 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004740 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004741 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004742 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004743 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004744 // FIXME: This should be type compatibility, e.g. whether
4745 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004746 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4747 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004748 if (LHSIface && RHSIface &&
4749 canAssignObjCInterfaces(LHSIface, RHSIface))
4750 return LHS;
4751
Eli Friedman3d815e72008-08-22 00:56:42 +00004752 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004753 }
Steve Naroff14108da2009-07-10 23:34:53 +00004754 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004755 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4756 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004757 return LHS;
4758
Steve Naroffbc76dd02008-12-10 22:14:21 +00004759 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004760 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004761 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004762
4763 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004764}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004765
Chris Lattner5426bf62008-04-07 07:01:58 +00004766//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004767// Integer Predicates
4768//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004769
Eli Friedmanad74a752008-06-28 06:23:08 +00004770unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004771 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004772 return 1;
John McCall842aef82009-12-09 09:09:27 +00004773 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004774 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004775 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004776 return (unsigned)getTypeSize(T);
4777}
4778
4779QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4780 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004781
4782 // Turn <4 x signed int> -> <4 x unsigned int>
4783 if (const VectorType *VTy = T->getAs<VectorType>())
4784 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004785 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004786
4787 // For enums, we return the unsigned version of the base type.
4788 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004789 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004790
4791 const BuiltinType *BTy = T->getAs<BuiltinType>();
4792 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004793 switch (BTy->getKind()) {
4794 case BuiltinType::Char_S:
4795 case BuiltinType::SChar:
4796 return UnsignedCharTy;
4797 case BuiltinType::Short:
4798 return UnsignedShortTy;
4799 case BuiltinType::Int:
4800 return UnsignedIntTy;
4801 case BuiltinType::Long:
4802 return UnsignedLongTy;
4803 case BuiltinType::LongLong:
4804 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004805 case BuiltinType::Int128:
4806 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004807 default:
4808 assert(0 && "Unexpected signed integer type");
4809 return QualType();
4810 }
4811}
4812
Douglas Gregor2cf26342009-04-09 22:27:44 +00004813ExternalASTSource::~ExternalASTSource() { }
4814
4815void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004816
4817
4818//===----------------------------------------------------------------------===//
4819// Builtin Type Computation
4820//===----------------------------------------------------------------------===//
4821
4822/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4823/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004824static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004825 ASTContext::GetBuiltinTypeError &Error,
4826 bool AllowTypeModifiers = true) {
4827 // Modifiers.
4828 int HowLong = 0;
4829 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004830
Chris Lattner86df27b2009-06-14 00:45:47 +00004831 // Read the modifiers first.
4832 bool Done = false;
4833 while (!Done) {
4834 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004835 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004836 case 'S':
4837 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4838 assert(!Signed && "Can't use 'S' modifier multiple times!");
4839 Signed = true;
4840 break;
4841 case 'U':
4842 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4843 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4844 Unsigned = true;
4845 break;
4846 case 'L':
4847 assert(HowLong <= 2 && "Can't have LLLL modifier");
4848 ++HowLong;
4849 break;
4850 }
4851 }
4852
4853 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Chris Lattner86df27b2009-06-14 00:45:47 +00004855 // Read the base type.
4856 switch (*Str++) {
4857 default: assert(0 && "Unknown builtin type letter!");
4858 case 'v':
4859 assert(HowLong == 0 && !Signed && !Unsigned &&
4860 "Bad modifiers used with 'v'!");
4861 Type = Context.VoidTy;
4862 break;
4863 case 'f':
4864 assert(HowLong == 0 && !Signed && !Unsigned &&
4865 "Bad modifiers used with 'f'!");
4866 Type = Context.FloatTy;
4867 break;
4868 case 'd':
4869 assert(HowLong < 2 && !Signed && !Unsigned &&
4870 "Bad modifiers used with 'd'!");
4871 if (HowLong)
4872 Type = Context.LongDoubleTy;
4873 else
4874 Type = Context.DoubleTy;
4875 break;
4876 case 's':
4877 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4878 if (Unsigned)
4879 Type = Context.UnsignedShortTy;
4880 else
4881 Type = Context.ShortTy;
4882 break;
4883 case 'i':
4884 if (HowLong == 3)
4885 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4886 else if (HowLong == 2)
4887 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4888 else if (HowLong == 1)
4889 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4890 else
4891 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4892 break;
4893 case 'c':
4894 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4895 if (Signed)
4896 Type = Context.SignedCharTy;
4897 else if (Unsigned)
4898 Type = Context.UnsignedCharTy;
4899 else
4900 Type = Context.CharTy;
4901 break;
4902 case 'b': // boolean
4903 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4904 Type = Context.BoolTy;
4905 break;
4906 case 'z': // size_t.
4907 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4908 Type = Context.getSizeType();
4909 break;
4910 case 'F':
4911 Type = Context.getCFConstantStringType();
4912 break;
4913 case 'a':
4914 Type = Context.getBuiltinVaListType();
4915 assert(!Type.isNull() && "builtin va list type not initialized!");
4916 break;
4917 case 'A':
4918 // This is a "reference" to a va_list; however, what exactly
4919 // this means depends on how va_list is defined. There are two
4920 // different kinds of va_list: ones passed by value, and ones
4921 // passed by reference. An example of a by-value va_list is
4922 // x86, where va_list is a char*. An example of by-ref va_list
4923 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4924 // we want this argument to be a char*&; for x86-64, we want
4925 // it to be a __va_list_tag*.
4926 Type = Context.getBuiltinVaListType();
4927 assert(!Type.isNull() && "builtin va list type not initialized!");
4928 if (Type->isArrayType()) {
4929 Type = Context.getArrayDecayedType(Type);
4930 } else {
4931 Type = Context.getLValueReferenceType(Type);
4932 }
4933 break;
4934 case 'V': {
4935 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004936 unsigned NumElements = strtoul(Str, &End, 10);
4937 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Chris Lattner86df27b2009-06-14 00:45:47 +00004939 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Chris Lattner86df27b2009-06-14 00:45:47 +00004941 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004942 // FIXME: Don't know what to do about AltiVec.
4943 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004944 break;
4945 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004946 case 'X': {
4947 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4948 Type = Context.getComplexType(ElementType);
4949 break;
4950 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004951 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004952 Type = Context.getFILEType();
4953 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004954 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004955 return QualType();
4956 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004957 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004958 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004959 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004960 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004961 else
4962 Type = Context.getjmp_bufType();
4963
Mike Stumpfd612db2009-07-28 23:47:15 +00004964 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004965 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004966 return QualType();
4967 }
4968 break;
Mike Stump782fa302009-07-28 02:25:19 +00004969 }
Mike Stump1eb44332009-09-09 15:08:12 +00004970
Chris Lattner86df27b2009-06-14 00:45:47 +00004971 if (!AllowTypeModifiers)
4972 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004973
Chris Lattner86df27b2009-06-14 00:45:47 +00004974 Done = false;
4975 while (!Done) {
4976 switch (*Str++) {
4977 default: Done = true; --Str; break;
4978 case '*':
4979 Type = Context.getPointerType(Type);
4980 break;
4981 case '&':
4982 Type = Context.getLValueReferenceType(Type);
4983 break;
4984 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4985 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004986 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004987 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004988 case 'D':
4989 Type = Context.getVolatileType(Type);
4990 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004991 }
4992 }
Mike Stump1eb44332009-09-09 15:08:12 +00004993
Chris Lattner86df27b2009-06-14 00:45:47 +00004994 return Type;
4995}
4996
4997/// GetBuiltinType - Return the type for the specified builtin.
4998QualType ASTContext::GetBuiltinType(unsigned id,
4999 GetBuiltinTypeError &Error) {
5000 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005001
Chris Lattner86df27b2009-06-14 00:45:47 +00005002 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005003
Chris Lattner86df27b2009-06-14 00:45:47 +00005004 Error = GE_None;
5005 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5006 if (Error != GE_None)
5007 return QualType();
5008 while (TypeStr[0] && TypeStr[0] != '.') {
5009 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5010 if (Error != GE_None)
5011 return QualType();
5012
5013 // Do array -> pointer decay. The builtin should use the decayed type.
5014 if (Ty->isArrayType())
5015 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Chris Lattner86df27b2009-06-14 00:45:47 +00005017 ArgTypes.push_back(Ty);
5018 }
5019
5020 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5021 "'.' should only occur at end of builtin type list!");
5022
5023 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5024 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5025 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005026
5027 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005028 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005029 TypeStr[0] == '.', 0, false, false, 0, 0,
5030 false, CC_Default);
Chris Lattner86df27b2009-06-14 00:45:47 +00005031}
Eli Friedmana95d7572009-08-19 07:44:53 +00005032
5033QualType
5034ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5035 // Perform the usual unary conversions. We do this early so that
5036 // integral promotions to "int" can allow us to exit early, in the
5037 // lhs == rhs check. Also, for conversion purposes, we ignore any
5038 // qualifiers. For example, "const float" and "float" are
5039 // equivalent.
5040 if (lhs->isPromotableIntegerType())
5041 lhs = getPromotedIntegerType(lhs);
5042 else
5043 lhs = lhs.getUnqualifiedType();
5044 if (rhs->isPromotableIntegerType())
5045 rhs = getPromotedIntegerType(rhs);
5046 else
5047 rhs = rhs.getUnqualifiedType();
5048
5049 // If both types are identical, no conversion is needed.
5050 if (lhs == rhs)
5051 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005052
Eli Friedmana95d7572009-08-19 07:44:53 +00005053 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5054 // The caller can deal with this (e.g. pointer + int).
5055 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5056 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005057
5058 // At this point, we have two different arithmetic types.
5059
Eli Friedmana95d7572009-08-19 07:44:53 +00005060 // Handle complex types first (C99 6.3.1.8p1).
5061 if (lhs->isComplexType() || rhs->isComplexType()) {
5062 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005063 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005064 // convert the rhs to the lhs complex type.
5065 return lhs;
5066 }
Mike Stump1eb44332009-09-09 15:08:12 +00005067 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005068 // convert the lhs to the rhs complex type.
5069 return rhs;
5070 }
5071 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005072 // When both operands are complex, the shorter operand is converted to the
5073 // type of the longer, and that is the type of the result. This corresponds
5074 // to what is done when combining two real floating-point operands.
5075 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005076 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005077 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005078 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005079 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005080 // "double _Complex" is promoted to "long double _Complex".
5081 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005082
5083 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005084 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005085 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005086 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005087 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005088 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5089 // domains match. This is a requirement for our implementation, C99
5090 // does not require this promotion.
5091 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5092 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5093 return rhs;
5094 } else { // handle "_Complex double, double".
5095 return lhs;
5096 }
5097 }
5098 return lhs; // The domain/size match exactly.
5099 }
5100 // Now handle "real" floating types (i.e. float, double, long double).
5101 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5102 // if we have an integer operand, the result is the real floating type.
5103 if (rhs->isIntegerType()) {
5104 // convert rhs to the lhs floating point type.
5105 return lhs;
5106 }
5107 if (rhs->isComplexIntegerType()) {
5108 // convert rhs to the complex floating point type.
5109 return getComplexType(lhs);
5110 }
5111 if (lhs->isIntegerType()) {
5112 // convert lhs to the rhs floating point type.
5113 return rhs;
5114 }
Mike Stump1eb44332009-09-09 15:08:12 +00005115 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005116 // convert lhs to the complex floating point type.
5117 return getComplexType(rhs);
5118 }
5119 // We have two real floating types, float/complex combos were handled above.
5120 // Convert the smaller operand to the bigger result.
5121 int result = getFloatingTypeOrder(lhs, rhs);
5122 if (result > 0) // convert the rhs
5123 return lhs;
5124 assert(result < 0 && "illegal float comparison");
5125 return rhs; // convert the lhs
5126 }
5127 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5128 // Handle GCC complex int extension.
5129 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5130 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5131
5132 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005133 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005134 rhsComplexInt->getElementType()) >= 0)
5135 return lhs; // convert the rhs
5136 return rhs;
5137 } else if (lhsComplexInt && rhs->isIntegerType()) {
5138 // convert the rhs to the lhs complex type.
5139 return lhs;
5140 } else if (rhsComplexInt && lhs->isIntegerType()) {
5141 // convert the lhs to the rhs complex type.
5142 return rhs;
5143 }
5144 }
5145 // Finally, we have two differing integer types.
5146 // The rules for this case are in C99 6.3.1.8
5147 int compare = getIntegerTypeOrder(lhs, rhs);
5148 bool lhsSigned = lhs->isSignedIntegerType(),
5149 rhsSigned = rhs->isSignedIntegerType();
5150 QualType destType;
5151 if (lhsSigned == rhsSigned) {
5152 // Same signedness; use the higher-ranked type
5153 destType = compare >= 0 ? lhs : rhs;
5154 } else if (compare != (lhsSigned ? 1 : -1)) {
5155 // The unsigned type has greater than or equal rank to the
5156 // signed type, so use the unsigned type
5157 destType = lhsSigned ? rhs : lhs;
5158 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5159 // The two types are different widths; if we are here, that
5160 // means the signed type is larger than the unsigned type, so
5161 // use the signed type.
5162 destType = lhsSigned ? lhs : rhs;
5163 } else {
5164 // The signed type is higher-ranked than the unsigned type,
5165 // but isn't actually any bigger (like unsigned int and long
5166 // on most 32-bit systems). Use the unsigned type corresponding
5167 // to the signed type.
5168 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5169 }
5170 return destType;
5171}