blob: f134bfdf1f24e5795bfc6c107ef420cd5a8c51bc [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner465fa322008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump11289f42009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump11289f42009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall9f57c292009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000056}
57
Chris Lattnerd5973eb2006-11-12 00:53:46 +000058ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-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 Kremenekda4e0d32010-02-11 07:12:28 +000068
Ted Kremenek40ee0cc2009-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 Friedmane2bbfe22008-05-27 03:08:09 +000075
Ted Kremenek40ee0cc2009-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 McCall8ccfcb52009-09-24 19:53:00 +000079 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000080 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000081
Ted Kremenekc3015a92010-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 Kremenek40ee0cc2009-12-23 21:13:52 +000088
Ted Kremenekc3015a92010-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 Lopese013c7f2008-12-17 22:30:25 +000096 }
97
Douglas Gregorf21eb492009-03-26 23:50:42 +000098 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +000099 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
100 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000101 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000102 NNS != NNSEnd; ) {
103 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000104 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000105 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000106
107 if (GlobalNestedNameSpecifier)
108 GlobalNestedNameSpecifier->Destroy(*this);
109
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000110 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000111}
112
Mike Stump11289f42009-09-09 15:08:12 +0000113void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000114ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
115 ExternalSource.reset(Source.take());
116}
117
Chris Lattner4eb445d2007-01-26 01:27:23 +0000118void ASTContext::PrintStats() const {
119 fprintf(stderr, "*** AST Context Stats:\n");
120 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000121
Douglas Gregora30d0462009-05-26 14:40:08 +0000122 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000123#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000124#define ABSTRACT_TYPE(Name, Parent)
125#include "clang/AST/TypeNodes.def"
126 0 // Extra
127 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000128
Chris Lattner4eb445d2007-01-26 01:27:23 +0000129 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
130 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000131 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000132 }
133
Douglas Gregora30d0462009-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 Stump11289f42009-09-09 15:08:12 +0000143
Douglas Gregora30d0462009-05-26 14:40:08 +0000144 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000145
146 if (ExternalSource.get()) {
147 fprintf(stderr, "\n");
148 ExternalSource->PrintStats();
149 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000150}
151
152
John McCall48f2d582009-10-23 23:03:21 +0000153void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000154 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000155 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000156 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000157}
158
Chris Lattner970e54e2006-11-12 00:37:36 +0000159void ASTContext::InitBuiltinTypes() {
160 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000161
Chris Lattner970e54e2006-11-12 00:37:36 +0000162 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000163 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattner970e54e2006-11-12 00:37:36 +0000165 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000166 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000167 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000168 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000169 InitBuiltinType(CharTy, BuiltinType::Char_S);
170 else
171 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000172 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000173 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 Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner970e54e2006-11-12 00:37:36 +0000179 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000180 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 Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner970e54e2006-11-12 00:37:36 +0000186 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000187 InitBuiltinType(FloatTy, BuiltinType::Float);
188 InitBuiltinType(DoubleTy, BuiltinType::Double);
189 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000190
Chris Lattnerf122cef2009-04-30 02:43:43 +0000191 // GNU extension, 128-bit integers.
192 InitBuiltinType(Int128Ty, BuiltinType::Int128);
193 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
194
Chris Lattner007cb022009-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 Kyrtzidis40e9e482008-08-09 16:51:54 +0000199
Alisdair Mereditha9ad47d2009-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 Gregor5251f1b2008-10-21 16:13:35 +0000210 // Placeholder type for functions.
Douglas Gregor4619e432008-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 Gregor5251f1b2008-10-21 16:13:35 +0000219
Mike Stump11289f42009-09-09 15:08:12 +0000220 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000221 // not yet been deduced.
222 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner970e54e2006-11-12 00:37:36 +0000224 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000225 FloatComplexTy = getComplexType(FloatTy);
226 DoubleComplexTy = getComplexType(DoubleTy);
227 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228
Steve Naroff66e9f332007-10-15 14:41:52 +0000229 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000230
Steve Naroff1329fa02009-07-15 18:40:39 +0000231 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
232 ObjCIdTypedefType = QualType();
233 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000234 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000235
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000236 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000237 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
238 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000239 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000240
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000241 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000242
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000243 // void * type
244 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000245
246 // nullptr type (C++0x 2.14.7)
247 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000248}
249
Douglas Gregor86d142a2009-10-08 07:24:58 +0000250MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000251ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000252 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000253 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000254 = InstantiatedFromStaticDataMember.find(Var);
255 if (Pos == InstantiatedFromStaticDataMember.end())
256 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000257
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000258 return Pos->second;
259}
260
Mike Stump11289f42009-09-09 15:08:12 +0000261void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000262ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
263 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-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 Gregor86d142a2009-10-08 07:24:58 +0000268 InstantiatedFromStaticDataMember[Inst]
269 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000270}
271
John McCalle61f2ba2009-11-18 02:36:19 +0000272NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000273ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000274 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000275 = InstantiatedFromUsingDecl.find(UUD);
276 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000277 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000278
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000279 return Pos->second;
280}
281
282void
John McCallb96ec562009-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 Carlsson4bb87ce2009-08-29 19:37:28 +0000307}
308
Anders Carlsson5da84842009-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 Stump11289f42009-09-09 15:08:12 +0000314
Anders Carlsson5da84842009-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 Stump11289f42009-09-09 15:08:12 +0000324
Anders Carlsson5da84842009-09-01 04:26:58 +0000325 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
326}
327
Douglas Gregor832940b2010-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 Gregorc6d5edd2009-07-02 17:08:52 +0000402namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000403 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000404 : std::binary_function<SourceRange, SourceRange, bool> {
405 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000406
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000407 public:
408 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000409
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000425static bool
426isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000427 bool Member = false) {
Mike Stump11289f42009-09-09 15:08:12 +0000428 const char *BufferStart
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000432
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000446/// it has one.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000447const char *ASTContext::getCommentForDecl(const Decl *D) {
448 if (!D)
449 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000450
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000451 // Check whether we have cached a comment string for this declaration
452 // already.
Mike Stump11289f42009-09-09 15:08:12 +0000453 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000454 = DeclComments.find(D);
455 if (Pos != DeclComments.end())
456 return Pos->second.c_str();
457
Mike Stump11289f42009-09-09 15:08:12 +0000458 // If we have an external AST source and have not yet loaded comments from
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000463
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000464 if (!LoadedComments.empty())
465 Comments.insert(Comments.begin(), LoadedComments.begin(),
466 LoadedComments.end());
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 LoadedExternalComments = true;
469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
471 // If there are no comments anywhere, we won't find anything.
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000483 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000484 SourceRange(DeclStartLoc),
485 BeforeInTranslationUnit(&SourceMgr));
Mike Stump11289f42009-09-09 15:08:12 +0000486
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000489 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000490 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000491 const char *FileBufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000492 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000502 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000508 Result.append(FileBufferStart +
509 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000510 FileBufferStart + LastCommentEndDecomp.second + 1);
511 return Result.c_str();
512 }
513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000522
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000528 // Check that we actually have a Doxygen comment.
529 if (!isDoxygenComment(SourceMgr, *LastComment))
530 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000531
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000534 unsigned DeclStartLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000535 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
536 unsigned CommentEndLine
Mike Stump11289f42009-09-09 15:08:12 +0000537 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000538 LastCommentEndDecomp.second);
Mike Stump11289f42009-09-09 15:08:12 +0000539
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000544
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000548 unsigned ExpectedLine
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000556
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000562
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000568
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000576 // Set the next expected line number.
Mike Stump11289f42009-09-09 15:08:12 +0000577 ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000578 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
579 }
Mike Stump11289f42009-09-09 15:08:12 +0000580
Douglas Gregorc6d5edd2009-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 Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000596 // Append the last comment line.
Mike Stump11289f42009-09-09 15:08:12 +0000597 Result.append(FileBufferStart +
598 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000599 FileBufferStart + LastCommentEndDecomp.second + 1);
600 return Result.c_str();
601}
602
Chris Lattner53cfe802007-07-18 17:52:12 +0000603//===----------------------------------------------------------------------===//
604// Type Sizing and Analysis
605//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000606
Chris Lattner9a8d1d92008-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 McCall9dd450b2009-09-21 23:43:11 +0000610 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-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 Dyck160146e2010-01-27 17:10:57 +0000620/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-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 Redl22e2e5c2009-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 Dyck160146e2010-01-27 17:10:57 +0000625CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000626 unsigned Align = Target.getCharWidth();
627
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000628 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000629 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000630
Chris Lattner68061312009-01-24 21:53:27 +0000631 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
632 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000633 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-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 Carlsson9b5038e2009-04-10 04:47:03 +0000640 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-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 Davis3fc51072010-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 Lattner68061312009-01-24 21:53:27 +0000652 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000653
Ken Dyck160146e2010-01-27 17:10:57 +0000654 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000655}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000656
Chris Lattner983a8bb2007-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 McCall8ccfcb52009-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 Lattner4481b422007-07-14 01:29:45 +0000663std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000664ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000665 uint64_t Width=0;
666 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000667 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000668#define TYPE(Class, Base)
669#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000670#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
672#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000673 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000674 break;
675
Chris Lattner355332d2007-07-13 22:27:08 +0000676 case Type::FunctionNoProto:
677 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000678 // GCC extension: alignof(function) = 32 bits
679 Width = 0;
680 Align = 32;
681 break;
682
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000683 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000684 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000685 Width = 0;
686 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
687 break;
688
Steve Naroff5c131802007-08-30 01:06:46 +0000689 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000690 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner37e05872008-03-05 18:54:05 +0000692 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000693 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000694 Align = EltInfo.second;
695 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000696 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000697 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000698 case Type::Vector: {
Chris Lattner63d2b362009-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 Friedman3df5efe2008-05-30 09:31:38 +0000702 Align = Width;
Nate Begemanb699c9b2009-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 Lattner63d2b362009-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 Lattnerf2e101f2007-07-19 22:06:24 +0000709 break;
710 }
Chris Lattner647fb222007-07-18 18:26:58 +0000711
Chris Lattner7570e9c2008-03-08 08:52:55 +0000712 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000713 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000714 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000715 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000716 // GCC extension: alignof(void) = 8 bits.
717 Width = 0;
718 Align = 8;
719 break;
720
Chris Lattner6a4f7452007-12-19 19:23:28 +0000721 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 Width = Target.getBoolWidth();
723 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000724 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000725 case BuiltinType::Char_S:
726 case BuiltinType::Char_U:
727 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000728 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000729 Width = Target.getCharWidth();
730 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000731 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000732 case BuiltinType::WChar:
733 Width = Target.getWCharWidth();
734 Align = Target.getWCharAlign();
735 break;
Alisdair Mereditha9ad47d2009-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 Lattner355332d2007-07-13 22:27:08 +0000744 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000745 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000746 Width = Target.getShortWidth();
747 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000748 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000749 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000751 Width = Target.getIntWidth();
752 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000753 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000754 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000755 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000756 Width = Target.getLongWidth();
757 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000758 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000759 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000760 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000761 Width = Target.getLongLongWidth();
762 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000763 break;
Chris Lattner0a415ec2009-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 Lattner6a4f7452007-12-19 19:23:28 +0000769 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000770 Width = Target.getFloatWidth();
771 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000772 break;
773 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000774 Width = Target.getDoubleWidth();
775 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000776 break;
777 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000778 Width = Target.getLongDoubleWidth();
779 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 break;
Sebastian Redl576fd422009-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 Redla81b0b72009-05-27 19:34:06 +0000784 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000785 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000786 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000787 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000788 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000789 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000790 break;
Steve Naroff921a45c2008-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 Redl22e2e5c2009-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 Lattner2dca6ff2008-03-08 08:34:58 +0000806 case Type::Pointer: {
807 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000808 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000809 Align = Target.getPointerAlign(AS);
810 break;
811 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000812 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000813 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000814 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000815 getTypeInfo(getPointerDiffType());
816 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000817 if (Pointee->isFunctionType())
818 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000819 Align = PtrDiffInfo.second;
820 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000821 }
Chris Lattner647fb222007-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 Stump11289f42009-09-09 15:08:12 +0000825 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000826 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000827 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000828 Align = EltInfo.second;
829 break;
830 }
Devang Pateldbb72632008-06-04 21:54:36 +0000831 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000832 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000833 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
834 Width = Layout.getSize();
835 Align = Layout.getAlignment();
836 break;
837 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000838 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000839 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000840 const TagType *TT = cast<TagType>(T);
841
842 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000843 Width = 1;
844 Align = 1;
845 break;
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000848 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000849 return getTypeInfo(ET->getDecl()->getIntegerType());
850
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000851 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000852 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
853 Width = Layout.getSize();
854 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000855 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000856 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000857
Chris Lattner63d2b362009-10-22 05:17:15 +0000858 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000859 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
860 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000861
Chris Lattner63d2b362009-10-22 05:17:15 +0000862 case Type::Elaborated:
863 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
864 .getTypePtr());
John McCallfcc33b02009-09-05 00:15:47 +0000865
Douglas Gregoref462e62009-04-30 17:32:17 +0000866 case Type::Typedef: {
867 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000868 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000869 Align = std::max(Aligned->getMaxAlignment(),
870 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000871 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
872 } else
873 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000874 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000875 }
Douglas Gregoref462e62009-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 Carlsson81df7b82009-06-24 19:06:50 +0000884 case Type::Decltype:
885 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
886 .getTypePtr());
887
Douglas Gregoref462e62009-04-30 17:32:17 +0000888 case Type::QualifiedName:
889 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000890
John McCalle78aac42010-03-10 03:28:59 +0000891 case Type::InjectedClassName:
892 return getTypeInfo(cast<InjectedClassNameType>(T)
893 ->getUnderlyingType().getTypePtr());
894
Douglas Gregoref462e62009-04-30 17:32:17 +0000895 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000896 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-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 Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner53cfe802007-07-18 17:52:12 +0000904 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000905 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000906}
907
Ken Dyck8c89d592009-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 Dyck40775002010-01-11 17:06:35 +0000911 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000912}
913CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000914 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000915}
916
Ken Dycka6046ab2010-01-26 17:25:18 +0000917/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-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 Lattnera3402cd2009-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 Friedman7ab09572009-05-25 21:27:19 +0000932
933 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000934 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-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 Lattnera3402cd2009-01-27 18:08:34 +0000940 return ABIAlign;
941}
942
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000943static void CollectLocalObjCIvars(ASTContext *Ctx,
944 const ObjCInterfaceDecl *OI,
945 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000946 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
947 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000948 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000949 if (!IVDecl->isInvalidDecl())
950 Fields.push_back(cast<FieldDecl>(IVDecl));
951 }
952}
953
Daniel Dunbare4f25b72009-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 Jahanian7c809592009-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 Jahanianaef66222010-02-19 00:31:17 +0000965 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-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 Jahanianaef66222010-02-19 00:31:17 +0000970
971 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000972}
973
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000974void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
975 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000976 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
977 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000978 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
979 Ivars.push_back(Ivar);
Mike Stump11289f42009-09-09 15:08:12 +0000980
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000981 // Also look into nested protocols.
982 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
983 E = PD->protocol_end(); P != E; ++P)
984 CollectProtocolSynthesizedIvars(*P, Ivars);
985}
986
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000987/// CollectNonClassIvars -
988/// This routine collects all other ivars which are not declared in the class.
989/// This includes synthesized ivars and those in class's implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000990///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000991void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000992 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000993 // Find ivars declared in class extension.
994 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
995 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
996 E = CDecl->ivar_end(); I != E; ++I) {
997 Ivars.push_back(*I);
998 }
999 }
1000
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001001 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1002 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001003 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
1004 Ivars.push_back(Ivar);
1005 }
1006 // Also look into interface's protocol list for properties declared
1007 // in the protocol and whose ivars are synthesized.
1008 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1009 PE = OI->protocol_end(); P != PE; ++P) {
1010 ObjCProtocolDecl *PD = (*P);
1011 CollectProtocolSynthesizedIvars(PD, Ivars);
1012 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001013
1014 // Also add any ivar defined in this class's implementation
1015 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1016 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1017 E = ImplDecl->ivar_end(); I != E; ++I)
1018 Ivars.push_back(*I);
1019 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001020}
1021
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001022/// CollectInheritedProtocols - Collect all protocols in current class and
1023/// those inherited by it.
1024void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001025 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001026 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1027 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1028 PE = OI->protocol_end(); P != PE; ++P) {
1029 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001030 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001031 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001032 PE = Proto->protocol_end(); P != PE; ++P) {
1033 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001034 CollectInheritedProtocols(*P, Protocols);
1035 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001036 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001037
1038 // Categories of this Interface.
1039 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1040 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1041 CollectInheritedProtocols(CDeclChain, Protocols);
1042 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1043 while (SD) {
1044 CollectInheritedProtocols(SD, Protocols);
1045 SD = SD->getSuperClass();
1046 }
1047 return;
1048 }
1049 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1050 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1051 PE = OC->protocol_end(); P != PE; ++P) {
1052 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001053 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001054 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1055 PE = Proto->protocol_end(); P != PE; ++P)
1056 CollectInheritedProtocols(*P, Protocols);
1057 }
1058 return;
1059 }
1060 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1061 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1062 PE = OP->protocol_end(); P != PE; ++P) {
1063 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001064 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001065 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1066 PE = Proto->protocol_end(); P != PE; ++P)
1067 CollectInheritedProtocols(*P, Protocols);
1068 }
1069 return;
1070 }
1071}
1072
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001073unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1074 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001075 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1076 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001077 if ((*I)->getPropertyIvarDecl())
1078 ++count;
1079
1080 // Also look into nested protocols.
1081 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1082 E = PD->protocol_end(); P != E; ++P)
1083 count += CountProtocolSynthesizedIvars(*P);
1084 return count;
1085}
1086
Mike Stump11289f42009-09-09 15:08:12 +00001087unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001088 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001089 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1090 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001091 if ((*I)->getPropertyIvarDecl())
1092 ++count;
1093 }
1094 // Also look into interface's protocol list for properties declared
1095 // in the protocol and whose ivars are synthesized.
1096 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1097 PE = OI->protocol_end(); P != PE; ++P) {
1098 ObjCProtocolDecl *PD = (*P);
1099 count += CountProtocolSynthesizedIvars(PD);
1100 }
1101 return count;
1102}
1103
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001104/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1105ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1106 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1107 I = ObjCImpls.find(D);
1108 if (I != ObjCImpls.end())
1109 return cast<ObjCImplementationDecl>(I->second);
1110 return 0;
1111}
1112/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1113ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1114 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1115 I = ObjCImpls.find(D);
1116 if (I != ObjCImpls.end())
1117 return cast<ObjCCategoryImplDecl>(I->second);
1118 return 0;
1119}
1120
1121/// \brief Set the implementation of ObjCInterfaceDecl.
1122void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1123 ObjCImplementationDecl *ImplD) {
1124 assert(IFaceD && ImplD && "Passed null params");
1125 ObjCImpls[IFaceD] = ImplD;
1126}
1127/// \brief Set the implementation of ObjCCategoryDecl.
1128void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1129 ObjCCategoryImplDecl *ImplD) {
1130 assert(CatD && ImplD && "Passed null params");
1131 ObjCImpls[CatD] = ImplD;
1132}
1133
John McCallbcd03502009-12-07 02:54:59 +00001134/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001135///
John McCallbcd03502009-12-07 02:54:59 +00001136/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001137/// the TypeLoc wrappers.
1138///
1139/// \param T the type that will be the basis for type source info. This type
1140/// should refer to how the declarator was written in source code, not to
1141/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001142TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001143 unsigned DataSize) {
1144 if (!DataSize)
1145 DataSize = TypeLoc::getFullDataSizeForType(T);
1146 else
1147 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001148 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001149
John McCallbcd03502009-12-07 02:54:59 +00001150 TypeSourceInfo *TInfo =
1151 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1152 new (TInfo) TypeSourceInfo(T);
1153 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001154}
1155
John McCallbcd03502009-12-07 02:54:59 +00001156TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001157 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001158 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001159 DI->getTypeLoc().initialize(L);
1160 return DI;
1161}
1162
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001163/// getInterfaceLayoutImpl - Get or compute information about the
1164/// layout of the given interface.
1165///
1166/// \param Impl - If given, also include the layout of the interface's
1167/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +00001168const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001169ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1170 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +00001171 assert(!D->isForwardDecl() && "Invalid interface decl!");
1172
Devang Pateldbb72632008-06-04 21:54:36 +00001173 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +00001174 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001175 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1176 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1177 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +00001178
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001179 // Add in synthesized ivar count if laying out an implementation.
1180 if (Impl) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001181 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001182 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001183 // entry. Note we can't cache this because we simply free all
1184 // entries later; however we shouldn't look up implementations
1185 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001186 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001187 return getObjCLayout(D, 0);
1188 }
1189
Mike Stump11289f42009-09-09 15:08:12 +00001190 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001191 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1192 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001193
Devang Pateldbb72632008-06-04 21:54:36 +00001194 return *NewEntry;
1195}
1196
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001197const ASTRecordLayout &
1198ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1199 return getObjCLayout(D, 0);
1200}
1201
1202const ASTRecordLayout &
1203ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1204 return getObjCLayout(D->getClassInterface(), D);
1205}
1206
Devang Patele11664a2007-11-01 19:11:01 +00001207/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +00001208/// specified record (struct/union/class), which indicates its size and field
1209/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +00001210const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001211 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +00001212 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +00001213
Chris Lattner53cfe802007-07-18 17:52:12 +00001214 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +00001215 // Note that we can't save a reference to the entry because this function
1216 // is recursive.
1217 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +00001218 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +00001219
Mike Stump11289f42009-09-09 15:08:12 +00001220 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001221 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +00001222 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001223
Chris Lattner647fb222007-07-18 18:26:58 +00001224 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +00001225}
1226
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001227const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001228 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001229 assert(RD && "Cannot get key function for forward declarations!");
1230
1231 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1232 if (!Entry)
1233 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1234 else
1235 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1236 "Key function changed!");
1237
1238 return Entry;
1239}
1240
Chris Lattner983a8bb2007-07-13 22:13:22 +00001241//===----------------------------------------------------------------------===//
1242// Type creation/memoization methods
1243//===----------------------------------------------------------------------===//
1244
John McCall8ccfcb52009-09-24 19:53:00 +00001245QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1246 unsigned Fast = Quals.getFastQualifiers();
1247 Quals.removeFastQualifiers();
1248
1249 // Check if we've already instantiated this type.
1250 llvm::FoldingSetNodeID ID;
1251 ExtQuals::Profile(ID, TypeNode, Quals);
1252 void *InsertPos = 0;
1253 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1254 assert(EQ->getQualifiers() == Quals);
1255 QualType T = QualType(EQ, Fast);
1256 return T;
1257 }
1258
John McCall90d1c2d2009-09-24 23:30:46 +00001259 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001260 ExtQualNodes.InsertNode(New, InsertPos);
1261 QualType T = QualType(New, Fast);
1262 return T;
1263}
1264
1265QualType ASTContext::getVolatileType(QualType T) {
1266 QualType CanT = getCanonicalType(T);
1267 if (CanT.isVolatileQualified()) return T;
1268
1269 QualifierCollector Quals;
1270 const Type *TypeNode = Quals.strip(T);
1271 Quals.addVolatile();
1272
1273 return getExtQualType(TypeNode, Quals);
1274}
1275
Fariborz Jahanianece85822009-02-17 18:27:45 +00001276QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001277 QualType CanT = getCanonicalType(T);
1278 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001279 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001280
John McCall8ccfcb52009-09-24 19:53:00 +00001281 // If we are composing extended qualifiers together, merge together
1282 // into one ExtQuals node.
1283 QualifierCollector Quals;
1284 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001285
John McCall8ccfcb52009-09-24 19:53:00 +00001286 // If this type already has an address space specified, it cannot get
1287 // another one.
1288 assert(!Quals.hasAddressSpace() &&
1289 "Type cannot be in multiple addr spaces!");
1290 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001291
John McCall8ccfcb52009-09-24 19:53:00 +00001292 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001293}
1294
Chris Lattnerd60183d2009-02-18 22:53:11 +00001295QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001296 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001297 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001298 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001299 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001300
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001301 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001302 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001303 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001304 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1305 return getPointerType(ResultType);
1306 }
1307 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
John McCall8ccfcb52009-09-24 19:53:00 +00001309 // If we are composing extended qualifiers together, merge together
1310 // into one ExtQuals node.
1311 QualifierCollector Quals;
1312 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001313
John McCall8ccfcb52009-09-24 19:53:00 +00001314 // If this type already has an ObjCGC specified, it cannot get
1315 // another one.
1316 assert(!Quals.hasObjCGCAttr() &&
1317 "Type cannot have multiple ObjCGCs!");
1318 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001319
John McCall8ccfcb52009-09-24 19:53:00 +00001320 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001321}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001322
Douglas Gregor8c940862010-01-18 17:14:39 +00001323static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1324 bool AddNoReturn,
1325 CallingConv CallConv) {
John McCall8ccfcb52009-09-24 19:53:00 +00001326 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001327 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1328 QualType Pointee = Pointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001329 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1330 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001331 if (ResultType == Pointee)
1332 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001333
1334 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001335 } else if (const BlockPointerType *BlockPointer
1336 = T->getAs<BlockPointerType>()) {
1337 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001338 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1339 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001340 if (ResultType == Pointee)
1341 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001342
1343 ResultType = Context.getBlockPointerType(ResultType);
1344 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1345 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001346 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001347
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001348 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001349 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1350 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001351 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001352 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001353 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001354 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1355 FPT->getNumArgs(), FPT->isVariadic(),
1356 FPT->getTypeQuals(),
1357 FPT->hasExceptionSpec(),
1358 FPT->hasAnyExceptionSpec(),
1359 FPT->getNumExceptions(),
1360 FPT->exception_begin(),
1361 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001362 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001363 } else
1364 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001365
1366 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1367}
1368
1369QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1370 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1371}
1372
1373QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1374 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump8c5d7992009-07-25 21:26:53 +00001375}
1376
Chris Lattnerc6395932007-06-22 20:56:16 +00001377/// getComplexType - Return the uniqued reference to the type for a complex
1378/// number with the specified element type.
1379QualType ASTContext::getComplexType(QualType T) {
1380 // Unique pointers, to guarantee there is only one pointer of a particular
1381 // structure.
1382 llvm::FoldingSetNodeID ID;
1383 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattnerc6395932007-06-22 20:56:16 +00001385 void *InsertPos = 0;
1386 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1387 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattnerc6395932007-06-22 20:56:16 +00001389 // If the pointee type isn't canonical, this won't be a canonical type either,
1390 // so fill in the canonical type field.
1391 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001392 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001393 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattnerc6395932007-06-22 20:56:16 +00001395 // Get the new insert position for the node we care about.
1396 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001397 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001398 }
John McCall90d1c2d2009-09-24 23:30:46 +00001399 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001400 Types.push_back(New);
1401 ComplexTypes.InsertNode(New, InsertPos);
1402 return QualType(New, 0);
1403}
1404
Chris Lattner970e54e2006-11-12 00:37:36 +00001405/// getPointerType - Return the uniqued reference to the type for a pointer to
1406/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001407QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001408 // Unique pointers, to guarantee there is only one pointer of a particular
1409 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001410 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001411 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001412
Chris Lattner67521df2007-01-27 01:29:36 +00001413 void *InsertPos = 0;
1414 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001415 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001416
Chris Lattner7ccecb92006-11-12 08:50:50 +00001417 // If the pointee type isn't canonical, this won't be a canonical type either,
1418 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001419 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001420 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001421 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001422
Chris Lattner67521df2007-01-27 01:29:36 +00001423 // Get the new insert position for the node we care about.
1424 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001425 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001426 }
John McCall90d1c2d2009-09-24 23:30:46 +00001427 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001428 Types.push_back(New);
1429 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001430 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001431}
1432
Mike Stump11289f42009-09-09 15:08:12 +00001433/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001434/// a pointer to the specified block.
1435QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001436 assert(T->isFunctionType() && "block of function types only");
1437 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001438 // structure.
1439 llvm::FoldingSetNodeID ID;
1440 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001441
Steve Naroffec33ed92008-08-27 16:04:49 +00001442 void *InsertPos = 0;
1443 if (BlockPointerType *PT =
1444 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1445 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001446
1447 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001448 // type either so fill in the canonical type field.
1449 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001450 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001451 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001452
Steve Naroffec33ed92008-08-27 16:04:49 +00001453 // Get the new insert position for the node we care about.
1454 BlockPointerType *NewIP =
1455 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001456 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001457 }
John McCall90d1c2d2009-09-24 23:30:46 +00001458 BlockPointerType *New
1459 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001460 Types.push_back(New);
1461 BlockPointerTypes.InsertNode(New, InsertPos);
1462 return QualType(New, 0);
1463}
1464
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001465/// getLValueReferenceType - Return the uniqued reference to the type for an
1466/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001467QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001468 // Unique pointers, to guarantee there is only one pointer of a particular
1469 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001470 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001471 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001472
1473 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001474 if (LValueReferenceType *RT =
1475 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001476 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001477
John McCallfc93cf92009-10-22 22:37:11 +00001478 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1479
Bill Wendling3708c182007-05-27 10:15:43 +00001480 // If the referencee type isn't canonical, this won't be a canonical type
1481 // either, so fill in the canonical type field.
1482 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001483 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1484 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1485 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001486
Bill Wendling3708c182007-05-27 10:15:43 +00001487 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001488 LValueReferenceType *NewIP =
1489 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001490 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001491 }
1492
John McCall90d1c2d2009-09-24 23:30:46 +00001493 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001494 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1495 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001496 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001497 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001498
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001499 return QualType(New, 0);
1500}
1501
1502/// getRValueReferenceType - Return the uniqued reference to the type for an
1503/// rvalue reference to the specified type.
1504QualType ASTContext::getRValueReferenceType(QualType T) {
1505 // Unique pointers, to guarantee there is only one pointer of a particular
1506 // structure.
1507 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001508 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001509
1510 void *InsertPos = 0;
1511 if (RValueReferenceType *RT =
1512 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1513 return QualType(RT, 0);
1514
John McCallfc93cf92009-10-22 22:37:11 +00001515 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1516
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001517 // If the referencee type isn't canonical, this won't be a canonical type
1518 // either, so fill in the canonical type field.
1519 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001520 if (InnerRef || !T.isCanonical()) {
1521 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1522 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001523
1524 // Get the new insert position for the node we care about.
1525 RValueReferenceType *NewIP =
1526 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1527 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1528 }
1529
John McCall90d1c2d2009-09-24 23:30:46 +00001530 RValueReferenceType *New
1531 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001532 Types.push_back(New);
1533 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001534 return QualType(New, 0);
1535}
1536
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001537/// getMemberPointerType - Return the uniqued reference to the type for a
1538/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001539QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001540 // Unique pointers, to guarantee there is only one pointer of a particular
1541 // structure.
1542 llvm::FoldingSetNodeID ID;
1543 MemberPointerType::Profile(ID, T, Cls);
1544
1545 void *InsertPos = 0;
1546 if (MemberPointerType *PT =
1547 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1548 return QualType(PT, 0);
1549
1550 // If the pointee or class type isn't canonical, this won't be a canonical
1551 // type either, so fill in the canonical type field.
1552 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001553 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001554 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1555
1556 // Get the new insert position for the node we care about.
1557 MemberPointerType *NewIP =
1558 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1559 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1560 }
John McCall90d1c2d2009-09-24 23:30:46 +00001561 MemberPointerType *New
1562 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001563 Types.push_back(New);
1564 MemberPointerTypes.InsertNode(New, InsertPos);
1565 return QualType(New, 0);
1566}
1567
Mike Stump11289f42009-09-09 15:08:12 +00001568/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001569/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001570QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001571 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001572 ArrayType::ArraySizeModifier ASM,
1573 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001574 assert((EltTy->isDependentType() ||
1575 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001576 "Constant array of VLAs is illegal!");
1577
Chris Lattnere2df3f92009-05-13 04:12:56 +00001578 // Convert the array size into a canonical width matching the pointer size for
1579 // the target.
1580 llvm::APInt ArySize(ArySizeIn);
1581 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001582
Chris Lattner23b7eb62007-06-15 23:05:46 +00001583 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001584 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001585
Chris Lattner36f8e652007-01-27 08:31:04 +00001586 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001587 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001588 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001589 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Chris Lattner7ccecb92006-11-12 08:50:50 +00001591 // If the element type isn't canonical, this won't be a canonical type either,
1592 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001593 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001594 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001595 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001596 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001597 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001598 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001599 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
John McCall90d1c2d2009-09-24 23:30:46 +00001603 ConstantArrayType *New = new(*this,TypeAlignment)
1604 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001605 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001606 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001607 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001608}
1609
Steve Naroffcadebd02007-08-30 18:14:25 +00001610/// getVariableArrayType - Returns a non-unique reference to the type for a
1611/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001612QualType ASTContext::getVariableArrayType(QualType EltTy,
1613 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001614 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001615 unsigned EltTypeQuals,
1616 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001617 // Since we don't unique expressions, it isn't possible to unique VLA's
1618 // that have an expression provided for their size.
1619
John McCall90d1c2d2009-09-24 23:30:46 +00001620 VariableArrayType *New = new(*this, TypeAlignment)
1621 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001622
1623 VariableArrayTypes.push_back(New);
1624 Types.push_back(New);
1625 return QualType(New, 0);
1626}
1627
Douglas Gregor4619e432008-12-05 23:32:09 +00001628/// getDependentSizedArrayType - Returns a non-unique reference to
1629/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001630/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001631QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1632 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001633 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001634 unsigned EltTypeQuals,
1635 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001636 assert((!NumElts || NumElts->isTypeDependent() ||
1637 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001638 "Size must be type- or value-dependent!");
1639
Douglas Gregorf3f95522009-07-31 00:23:35 +00001640 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001641 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001642 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001643
1644 if (NumElts) {
1645 // Dependently-sized array types that do not have a specified
1646 // number of elements will have their sizes deduced from an
1647 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001648 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1649 EltTypeQuals, NumElts);
1650
1651 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1652 }
1653
Douglas Gregorf3f95522009-07-31 00:23:35 +00001654 DependentSizedArrayType *New;
1655 if (Canon) {
1656 // We already have a canonical version of this array type; use it as
1657 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001658 New = new (*this, TypeAlignment)
1659 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1660 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001661 } else {
1662 QualType CanonEltTy = getCanonicalType(EltTy);
1663 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001664 New = new (*this, TypeAlignment)
1665 DependentSizedArrayType(*this, EltTy, QualType(),
1666 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001667
Douglas Gregorc42075a2010-02-04 18:10:26 +00001668 if (NumElts) {
1669 DependentSizedArrayType *CanonCheck
1670 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1671 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1672 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001673 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001674 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001675 } else {
1676 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1677 ASM, EltTypeQuals,
1678 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001679 New = new (*this, TypeAlignment)
1680 DependentSizedArrayType(*this, EltTy, Canon,
1681 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001682 }
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregor4619e432008-12-05 23:32:09 +00001685 Types.push_back(New);
1686 return QualType(New, 0);
1687}
1688
Eli Friedmanbd258282008-02-15 18:16:39 +00001689QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1690 ArrayType::ArraySizeModifier ASM,
1691 unsigned EltTypeQuals) {
1692 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001693 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001694
1695 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001696 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001697 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1698 return QualType(ATP, 0);
1699
1700 // If the element type isn't canonical, this won't be a canonical type
1701 // either, so fill in the canonical type field.
1702 QualType Canonical;
1703
John McCallb692a092009-10-22 20:10:53 +00001704 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001705 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001706 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001707
1708 // Get the new insert position for the node we care about.
1709 IncompleteArrayType *NewIP =
1710 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001711 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001712 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001713
John McCall90d1c2d2009-09-24 23:30:46 +00001714 IncompleteArrayType *New = new (*this, TypeAlignment)
1715 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001716
1717 IncompleteArrayTypes.InsertNode(New, InsertPos);
1718 Types.push_back(New);
1719 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001720}
1721
Steve Naroff91fcddb2007-07-18 18:00:27 +00001722/// getVectorType - Return the unique reference to a vector type of
1723/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001724QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1725 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001726 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Chris Lattner76a00cf2008-04-06 22:59:24 +00001728 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001729 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001730
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001731 // Check if we've already instantiated a vector of this type.
1732 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001733 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1734 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001735 void *InsertPos = 0;
1736 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1737 return QualType(VTP, 0);
1738
1739 // If the element type isn't canonical, this won't be a canonical type either,
1740 // so fill in the canonical type field.
1741 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001742 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1743 Canonical = getVectorType(getCanonicalType(vecType),
1744 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001745
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001746 // Get the new insert position for the node we care about.
1747 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001748 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001749 }
John McCall90d1c2d2009-09-24 23:30:46 +00001750 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001751 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001752 VectorTypes.InsertNode(New, InsertPos);
1753 Types.push_back(New);
1754 return QualType(New, 0);
1755}
1756
Nate Begemance4d7fc2008-04-18 23:10:10 +00001757/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001758/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001759QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001760 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001761
Chris Lattner76a00cf2008-04-06 22:59:24 +00001762 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001763 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001764
Steve Naroff91fcddb2007-07-18 18:00:27 +00001765 // Check if we've already instantiated a vector of this type.
1766 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001767 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001768 void *InsertPos = 0;
1769 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1770 return QualType(VTP, 0);
1771
1772 // If the element type isn't canonical, this won't be a canonical type either,
1773 // so fill in the canonical type field.
1774 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001775 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001776 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001777
Steve Naroff91fcddb2007-07-18 18:00:27 +00001778 // Get the new insert position for the node we care about.
1779 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001780 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001781 }
John McCall90d1c2d2009-09-24 23:30:46 +00001782 ExtVectorType *New = new (*this, TypeAlignment)
1783 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001784 VectorTypes.InsertNode(New, InsertPos);
1785 Types.push_back(New);
1786 return QualType(New, 0);
1787}
1788
Mike Stump11289f42009-09-09 15:08:12 +00001789QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001790 Expr *SizeExpr,
1791 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001792 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001793 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001794 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Douglas Gregor352169a2009-07-31 03:54:25 +00001796 void *InsertPos = 0;
1797 DependentSizedExtVectorType *Canon
1798 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1799 DependentSizedExtVectorType *New;
1800 if (Canon) {
1801 // We already have a canonical version of this array type; use it as
1802 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001803 New = new (*this, TypeAlignment)
1804 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1805 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001806 } else {
1807 QualType CanonVecTy = getCanonicalType(vecType);
1808 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001809 New = new (*this, TypeAlignment)
1810 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1811 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001812
1813 DependentSizedExtVectorType *CanonCheck
1814 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1815 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1816 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001817 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1818 } else {
1819 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1820 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001821 New = new (*this, TypeAlignment)
1822 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001823 }
1824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Douglas Gregor758a8692009-06-17 21:51:59 +00001826 Types.push_back(New);
1827 return QualType(New, 0);
1828}
1829
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001830/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001831///
Douglas Gregor8c940862010-01-18 17:14:39 +00001832QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1833 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001834 // Unique functions, to guarantee there is only one function of a particular
1835 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001836 llvm::FoldingSetNodeID ID;
John McCallcddbad02010-02-04 05:44:44 +00001837 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump11289f42009-09-09 15:08:12 +00001838
Chris Lattner47955de2007-01-27 08:37:20 +00001839 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001840 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001841 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001842 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001843
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001844 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001845 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001846 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001847 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001848 getCanonicalCallConv(CallConv));
Mike Stump11289f42009-09-09 15:08:12 +00001849
Chris Lattner47955de2007-01-27 08:37:20 +00001850 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001851 FunctionNoProtoType *NewIP =
1852 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001853 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
John McCall90d1c2d2009-09-24 23:30:46 +00001856 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallcddbad02010-02-04 05:44:44 +00001857 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Chris Lattner47955de2007-01-27 08:37:20 +00001858 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001859 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001860 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001861}
1862
1863/// getFunctionType - Return a normal function type with a typed argument
1864/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001865QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001866 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001867 unsigned TypeQuals, bool hasExceptionSpec,
1868 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregor8c940862010-01-18 17:14:39 +00001869 const QualType *ExArray, bool NoReturn,
1870 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001871 // Unique functions, to guarantee there is only one function of a particular
1872 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001873 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001874 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001875 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallcddbad02010-02-04 05:44:44 +00001876 NumExs, ExArray, NoReturn, CallConv);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001877
1878 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001879 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001880 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001881 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001882
1883 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001884 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001885 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001886 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001887 isCanonical = false;
1888
1889 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001890 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001891 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001892 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001893 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001894 CanonicalArgs.reserve(NumArgs);
1895 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001896 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001897
Chris Lattner76a00cf2008-04-06 22:59:24 +00001898 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001899 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001900 isVariadic, TypeQuals, false,
Douglas Gregor8c940862010-01-18 17:14:39 +00001901 false, 0, 0, NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001902 getCanonicalCallConv(CallConv));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001903
Chris Lattnerfd4de792007-01-27 01:15:32 +00001904 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001905 FunctionProtoType *NewIP =
1906 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001907 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001908 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001909
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001910 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001911 // for two variable size arrays (for parameter and exception types) at the
1912 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001913 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001914 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1915 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001916 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001917 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001918 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregor8c940862010-01-18 17:14:39 +00001919 ExArray, NumExs, Canonical, NoReturn, CallConv);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001920 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001921 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001922 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001923}
Chris Lattneref51c202006-11-10 07:17:23 +00001924
John McCalle78aac42010-03-10 03:28:59 +00001925#ifndef NDEBUG
1926static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1927 if (!isa<CXXRecordDecl>(D)) return false;
1928 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1929 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1930 return true;
1931 if (RD->getDescribedClassTemplate() &&
1932 !isa<ClassTemplateSpecializationDecl>(RD))
1933 return true;
1934 return false;
1935}
1936#endif
1937
1938/// getInjectedClassNameType - Return the unique reference to the
1939/// injected class name type for the specified templated declaration.
1940QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1941 QualType TST) {
1942 assert(NeedsInjectedClassNameType(Decl));
1943 if (Decl->TypeForDecl) {
1944 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1945 } else if (CXXRecordDecl *PrevDecl
1946 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1947 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1948 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1949 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1950 } else {
1951 Decl->TypeForDecl = new (*this, TypeAlignment)
1952 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1953 Types.push_back(Decl->TypeForDecl);
1954 }
1955 return QualType(Decl->TypeForDecl, 0);
1956}
1957
Douglas Gregor83a586e2008-04-13 21:07:44 +00001958/// getTypeDeclType - Return the unique reference to the type for the
1959/// specified type declaration.
John McCall81e38502010-02-16 03:57:14 +00001960QualType ASTContext::getTypeDeclType(const TypeDecl *Decl,
1961 const TypeDecl* PrevDecl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001962 assert(Decl && "Passed null for Decl param");
Douglas Gregor83a586e2008-04-13 21:07:44 +00001963 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001964
John McCall81e38502010-02-16 03:57:14 +00001965 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001966 return getTypedefType(Typedef);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001967 else if (isa<TemplateTypeParmDecl>(Decl)) {
1968 assert(false && "Template type parameter types are always available.");
John McCall81e38502010-02-16 03:57:14 +00001969 } else if (const ObjCInterfaceDecl *ObjCInterface
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001970 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001971 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001972
John McCall81e38502010-02-16 03:57:14 +00001973 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek721e2392009-01-19 21:31:22 +00001974 if (PrevDecl)
1975 Decl->TypeForDecl = PrevDecl->TypeForDecl;
John McCalle78aac42010-03-10 03:28:59 +00001976 else {
1977 assert(!NeedsInjectedClassNameType(Record));
John McCall90d1c2d2009-09-24 23:30:46 +00001978 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCalle78aac42010-03-10 03:28:59 +00001979 }
John McCall81e38502010-02-16 03:57:14 +00001980 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek721e2392009-01-19 21:31:22 +00001981 if (PrevDecl)
1982 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff096bab72009-01-27 22:08:43 +00001983 else
John McCall90d1c2d2009-09-24 23:30:46 +00001984 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001985 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001986 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1987 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001988 } else
Douglas Gregor83a586e2008-04-13 21:07:44 +00001989 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001990
Ted Kremenek21475702008-09-05 17:16:31 +00001991 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001992 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001993}
1994
Chris Lattner32d920b2007-01-26 02:01:53 +00001995/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001996/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001997QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001998 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001999
Chris Lattner76a00cf2008-04-06 22:59:24 +00002000 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00002001 Decl->TypeForDecl = new(*this, TypeAlignment)
2002 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00002003 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002004 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002005}
2006
John McCallcebee162009-10-18 09:09:24 +00002007/// \brief Retrieve a substitution-result type.
2008QualType
2009ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2010 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00002011 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002012 && "replacement types must always be canonical");
2013
2014 llvm::FoldingSetNodeID ID;
2015 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2016 void *InsertPos = 0;
2017 SubstTemplateTypeParmType *SubstParm
2018 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2019
2020 if (!SubstParm) {
2021 SubstParm = new (*this, TypeAlignment)
2022 SubstTemplateTypeParmType(Parm, Replacement);
2023 Types.push_back(SubstParm);
2024 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2025 }
2026
2027 return QualType(SubstParm, 0);
2028}
2029
Douglas Gregoreff93e02009-02-05 23:33:38 +00002030/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002031/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002032/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002033QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002034 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00002035 IdentifierInfo *Name) {
2036 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002037 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002038 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002039 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002040 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2041
2042 if (TypeParm)
2043 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002044
Anders Carlsson90036dc2009-06-16 00:30:48 +00002045 if (Name) {
2046 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00002047 TypeParm = new (*this, TypeAlignment)
2048 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002049
2050 TemplateTypeParmType *TypeCheck
2051 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2052 assert(!TypeCheck && "Template type parameter canonical type broken");
2053 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002054 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002055 TypeParm = new (*this, TypeAlignment)
2056 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002057
2058 Types.push_back(TypeParm);
2059 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2060
2061 return QualType(TypeParm, 0);
2062}
2063
John McCalle78aac42010-03-10 03:28:59 +00002064TypeSourceInfo *
2065ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2066 SourceLocation NameLoc,
2067 const TemplateArgumentListInfo &Args,
2068 QualType CanonType) {
2069 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2070
2071 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2072 TemplateSpecializationTypeLoc TL
2073 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2074 TL.setTemplateNameLoc(NameLoc);
2075 TL.setLAngleLoc(Args.getLAngleLoc());
2076 TL.setRAngleLoc(Args.getRAngleLoc());
2077 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2078 TL.setArgLocInfo(i, Args[i].getLocInfo());
2079 return DI;
2080}
2081
Mike Stump11289f42009-09-09 15:08:12 +00002082QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002083ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002084 const TemplateArgumentListInfo &Args,
John McCall0ad16662009-10-29 08:12:44 +00002085 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00002086 unsigned NumArgs = Args.size();
2087
John McCall0ad16662009-10-29 08:12:44 +00002088 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2089 ArgVec.reserve(NumArgs);
2090 for (unsigned i = 0; i != NumArgs; ++i)
2091 ArgVec.push_back(Args[i].getArgument());
2092
2093 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2094}
2095
2096QualType
2097ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002098 const TemplateArgument *Args,
2099 unsigned NumArgs,
2100 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00002101 if (!Canon.isNull())
2102 Canon = getCanonicalType(Canon);
2103 else {
2104 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002105 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2106 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2107 CanonArgs.reserve(NumArgs);
2108 for (unsigned I = 0; I != NumArgs; ++I)
2109 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2110
2111 // Determine whether this canonical template specialization type already
2112 // exists.
2113 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002114 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00002115 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002116
2117 void *InsertPos = 0;
2118 TemplateSpecializationType *Spec
2119 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002120
Douglas Gregora8e02e72009-07-28 23:00:59 +00002121 if (!Spec) {
2122 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00002123 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00002124 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002125 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002126 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00002127 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00002128 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002129 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002130 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002131 }
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregor15301382009-07-30 17:40:51 +00002133 if (Canon.isNull())
2134 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002135 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00002136 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00002137 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002138
Douglas Gregora8e02e72009-07-28 23:00:59 +00002139 // Allocate the (non-canonical) template specialization type, but don't
2140 // try to unique it: these types typically have location information that
2141 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002142 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002143 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002144 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002145 TemplateSpecializationType *Spec
2146 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002147 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002148
Douglas Gregor8bf42052009-02-09 18:46:07 +00002149 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002150 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002151}
2152
Mike Stump11289f42009-09-09 15:08:12 +00002153QualType
Douglas Gregorf21eb492009-03-26 23:50:42 +00002154ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor52537682009-03-19 00:18:19 +00002155 QualType NamedType) {
2156 llvm::FoldingSetNodeID ID;
Douglas Gregorf21eb492009-03-26 23:50:42 +00002157 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002158
2159 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002160 QualifiedNameType *T
Douglas Gregor52537682009-03-19 00:18:19 +00002161 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2162 if (T)
2163 return QualType(T, 0);
2164
Douglas Gregorc42075a2010-02-04 18:10:26 +00002165 QualType Canon = NamedType;
2166 if (!Canon.isCanonical()) {
2167 Canon = getCanonicalType(NamedType);
2168 QualifiedNameType *CheckT
2169 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 assert(!CheckT && "Qualified name canonical type broken");
2171 (void)CheckT;
2172 }
2173
2174 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002175 Types.push_back(T);
2176 QualifiedNameTypes.InsertNode(T, InsertPos);
2177 return QualType(T, 0);
2178}
2179
Mike Stump11289f42009-09-09 15:08:12 +00002180QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor333489b2009-03-27 23:10:48 +00002181 const IdentifierInfo *Name,
2182 QualType Canon) {
2183 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2184
2185 if (Canon.isNull()) {
2186 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2187 if (CanonNNS != NNS)
2188 Canon = getTypenameType(CanonNNS, Name);
2189 }
2190
2191 llvm::FoldingSetNodeID ID;
2192 TypenameType::Profile(ID, NNS, Name);
2193
2194 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002195 TypenameType *T
Douglas Gregor333489b2009-03-27 23:10:48 +00002196 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2197 if (T)
2198 return QualType(T, 0);
2199
2200 T = new (*this) TypenameType(NNS, Name, Canon);
2201 Types.push_back(T);
2202 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002203 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002204}
2205
Mike Stump11289f42009-09-09 15:08:12 +00002206QualType
2207ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregordce2b622009-04-01 00:28:59 +00002208 const TemplateSpecializationType *TemplateId,
2209 QualType Canon) {
2210 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2211
Douglas Gregorc42075a2010-02-04 18:10:26 +00002212 llvm::FoldingSetNodeID ID;
2213 TypenameType::Profile(ID, NNS, TemplateId);
2214
2215 void *InsertPos = 0;
2216 TypenameType *T
2217 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2218 if (T)
2219 return QualType(T, 0);
2220
Douglas Gregordce2b622009-04-01 00:28:59 +00002221 if (Canon.isNull()) {
2222 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2223 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2224 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2225 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00002226 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00002227 assert(CanonTemplateId &&
2228 "Canonical type must also be a template specialization type");
2229 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2230 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00002231
2232 TypenameType *CheckT
2233 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2234 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00002235 }
2236
Douglas Gregordce2b622009-04-01 00:28:59 +00002237 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2238 Types.push_back(T);
2239 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002240 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002241}
2242
John McCallfcc33b02009-09-05 00:15:47 +00002243QualType
2244ASTContext::getElaboratedType(QualType UnderlyingType,
2245 ElaboratedType::TagKind Tag) {
2246 llvm::FoldingSetNodeID ID;
2247 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00002248
John McCallfcc33b02009-09-05 00:15:47 +00002249 void *InsertPos = 0;
2250 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2251 if (T)
2252 return QualType(T, 0);
2253
Douglas Gregorc42075a2010-02-04 18:10:26 +00002254 QualType Canon = UnderlyingType;
2255 if (!Canon.isCanonical()) {
2256 Canon = getCanonicalType(Canon);
2257 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2258 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2259 }
John McCallfcc33b02009-09-05 00:15:47 +00002260
2261 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2262 Types.push_back(T);
2263 ElaboratedTypes.InsertNode(T, InsertPos);
2264 return QualType(T, 0);
2265}
2266
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002267/// CmpProtocolNames - Comparison predicate for sorting protocols
2268/// alphabetically.
2269static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2270 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002271 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002272}
2273
John McCallfc93cf92009-10-22 22:37:11 +00002274static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2275 unsigned NumProtocols) {
2276 if (NumProtocols == 0) return true;
2277
2278 for (unsigned i = 1; i != NumProtocols; ++i)
2279 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2280 return false;
2281 return true;
2282}
2283
2284static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002285 unsigned &NumProtocols) {
2286 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002288 // Sort protocols, keyed by name.
2289 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2290
2291 // Remove duplicates.
2292 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2293 NumProtocols = ProtocolsEnd-Protocols;
2294}
2295
Steve Narofffb4330f2009-06-17 22:40:22 +00002296/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2297/// the given interface decl and the conforming protocol list.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002298QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump11289f42009-09-09 15:08:12 +00002299 ObjCProtocolDecl **Protocols,
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002300 unsigned NumProtocols,
2301 unsigned Quals) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002302 llvm::FoldingSetNodeID ID;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002303 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002304 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Narofffb4330f2009-06-17 22:40:22 +00002305
2306 void *InsertPos = 0;
2307 if (ObjCObjectPointerType *QT =
2308 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002309 return getQualifiedType(QualType(QT, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002310
John McCallfc93cf92009-10-22 22:37:11 +00002311 // Sort the protocol list alphabetically to canonicalize it.
2312 QualType Canonical;
2313 if (!InterfaceT.isCanonical() ||
2314 !areSortedAndUniqued(Protocols, NumProtocols)) {
2315 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2316 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2317 unsigned UniqueCount = NumProtocols;
2318
2319 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2320 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2321
2322 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2323 &Sorted[0], UniqueCount);
2324 } else {
2325 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2326 Protocols, NumProtocols);
2327 }
2328
2329 // Regenerate InsertPos.
2330 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2331 }
2332
Douglas Gregorf85bee62010-02-08 22:59:26 +00002333 // No match.
2334 unsigned Size = sizeof(ObjCObjectPointerType)
2335 + NumProtocols * sizeof(ObjCProtocolDecl *);
2336 void *Mem = Allocate(Size, TypeAlignment);
2337 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2338 InterfaceT,
2339 Protocols,
2340 NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002341
Steve Narofffb4330f2009-06-17 22:40:22 +00002342 Types.push_back(QType);
2343 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002344 return getQualifiedType(QualType(QType, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002345}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002346
Steve Naroffc277ad12009-07-18 15:33:26 +00002347/// getObjCInterfaceType - Return the unique reference to the type for the
2348/// specified ObjC interface decl. The list of protocols is optional.
2349QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002350 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002351 llvm::FoldingSetNodeID ID;
Steve Naroffc277ad12009-07-18 15:33:26 +00002352 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002353
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002354 void *InsertPos = 0;
Steve Naroffc277ad12009-07-18 15:33:26 +00002355 if (ObjCInterfaceType *QT =
2356 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002357 return QualType(QT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002358
John McCallfc93cf92009-10-22 22:37:11 +00002359 // Sort the protocol list alphabetically to canonicalize it.
2360 QualType Canonical;
2361 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2362 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2363 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2364
2365 unsigned UniqueCount = NumProtocols;
2366 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2367
2368 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2369
2370 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2371 }
2372
Douglas Gregorf85bee62010-02-08 22:59:26 +00002373 unsigned Size = sizeof(ObjCInterfaceType)
2374 + NumProtocols * sizeof(ObjCProtocolDecl *);
2375 void *Mem = Allocate(Size, TypeAlignment);
2376 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2377 const_cast<ObjCInterfaceDecl*>(Decl),
2378 Protocols,
2379 NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002380
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002381 Types.push_back(QType);
Steve Naroffc277ad12009-07-18 15:33:26 +00002382 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002383 return QualType(QType, 0);
2384}
2385
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002386/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2387/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002388/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002389/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002390/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002391QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002392 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002393 if (tofExpr->isTypeDependent()) {
2394 llvm::FoldingSetNodeID ID;
2395 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002397 void *InsertPos = 0;
2398 DependentTypeOfExprType *Canon
2399 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2400 if (Canon) {
2401 // We already have a "canonical" version of an identical, dependent
2402 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002403 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002404 QualType((TypeOfExprType*)Canon, 0));
2405 }
2406 else {
2407 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002408 Canon
2409 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002410 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2411 toe = Canon;
2412 }
2413 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002414 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002415 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002416 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002417 Types.push_back(toe);
2418 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002419}
2420
Steve Naroffa773cd52007-08-01 18:02:17 +00002421/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2422/// TypeOfType AST's. The only motivation to unique these nodes would be
2423/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002424/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002425/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002426QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002427 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002428 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002429 Types.push_back(tot);
2430 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002431}
2432
Anders Carlssonad6bd352009-06-24 21:24:56 +00002433/// getDecltypeForExpr - Given an expr, will return the decltype for that
2434/// expression, according to the rules in C++0x [dcl.type.simple]p4
2435static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002436 if (e->isTypeDependent())
2437 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002438
Anders Carlssonad6bd352009-06-24 21:24:56 +00002439 // If e is an id expression or a class member access, decltype(e) is defined
2440 // as the type of the entity named by e.
2441 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2442 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2443 return VD->getType();
2444 }
2445 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2446 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2447 return FD->getType();
2448 }
2449 // If e is a function call or an invocation of an overloaded operator,
2450 // (parentheses around e are ignored), decltype(e) is defined as the
2451 // return type of that function.
2452 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2453 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002454
Anders Carlssonad6bd352009-06-24 21:24:56 +00002455 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002456
2457 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002458 // defined as T&, otherwise decltype(e) is defined as T.
2459 if (e->isLvalue(Context) == Expr::LV_Valid)
2460 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002461
Anders Carlssonad6bd352009-06-24 21:24:56 +00002462 return T;
2463}
2464
Anders Carlsson81df7b82009-06-24 19:06:50 +00002465/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2466/// DecltypeType AST's. The only motivation to unique these nodes would be
2467/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002468/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002469/// on canonical type's (which are always unique).
2470QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002471 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002472 if (e->isTypeDependent()) {
2473 llvm::FoldingSetNodeID ID;
2474 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002475
Douglas Gregora21f6c32009-07-30 23:36:40 +00002476 void *InsertPos = 0;
2477 DependentDecltypeType *Canon
2478 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2479 if (Canon) {
2480 // We already have a "canonical" version of an equivalent, dependent
2481 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002482 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002483 QualType((DecltypeType*)Canon, 0));
2484 }
2485 else {
2486 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002487 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002488 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2489 dt = Canon;
2490 }
2491 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002492 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002493 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002494 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002495 Types.push_back(dt);
2496 return QualType(dt, 0);
2497}
2498
Chris Lattnerfb072462007-01-23 05:45:31 +00002499/// getTagDeclType - Return the unique reference to the type for the
2500/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002501QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002502 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002503 // FIXME: What is the design on getTagDeclType when it requires casting
2504 // away const? mutable?
2505 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002506}
2507
Mike Stump11289f42009-09-09 15:08:12 +00002508/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2509/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2510/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002511CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002512 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002513}
Chris Lattnerfb072462007-01-23 05:45:31 +00002514
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002515/// getSignedWCharType - Return the type of "signed wchar_t".
2516/// Used when in C++, as a GCC extension.
2517QualType ASTContext::getSignedWCharType() const {
2518 // FIXME: derive from "Target" ?
2519 return WCharTy;
2520}
2521
2522/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2523/// Used when in C++, as a GCC extension.
2524QualType ASTContext::getUnsignedWCharType() const {
2525 // FIXME: derive from "Target" ?
2526 return UnsignedIntTy;
2527}
2528
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002529/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2530/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2531QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002532 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002533}
2534
Chris Lattnera21ad802008-04-02 05:18:44 +00002535//===----------------------------------------------------------------------===//
2536// Type Operators
2537//===----------------------------------------------------------------------===//
2538
John McCallfc93cf92009-10-22 22:37:11 +00002539CanQualType ASTContext::getCanonicalParamType(QualType T) {
2540 // Push qualifiers into arrays, and then discard any remaining
2541 // qualifiers.
2542 T = getCanonicalType(T);
2543 const Type *Ty = T.getTypePtr();
2544
2545 QualType Result;
2546 if (isa<ArrayType>(Ty)) {
2547 Result = getArrayDecayedType(QualType(Ty,0));
2548 } else if (isa<FunctionType>(Ty)) {
2549 Result = getPointerType(QualType(Ty, 0));
2550 } else {
2551 Result = QualType(Ty, 0);
2552 }
2553
2554 return CanQualType::CreateUnsafe(Result);
2555}
2556
Chris Lattnered0d0792008-04-06 22:41:35 +00002557/// getCanonicalType - Return the canonical (structural) type corresponding to
2558/// the specified potentially non-canonical type. The non-canonical version
2559/// of a type may have many "decorated" versions of types. Decorators can
2560/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2561/// to be free of any of these, allowing two canonical types to be compared
2562/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002563CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002564 QualifierCollector Quals;
2565 const Type *Ptr = Quals.strip(T);
2566 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002567
John McCall8ccfcb52009-09-24 19:53:00 +00002568 // The canonical internal type will be the canonical type *except*
2569 // that we push type qualifiers down through array types.
2570
2571 // If there are no new qualifiers to push down, stop here.
2572 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002573 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002574
John McCall8ccfcb52009-09-24 19:53:00 +00002575 // If the type qualifiers are on an array type, get the canonical
2576 // type of the array with the qualifiers applied to the element
2577 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002578 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2579 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002580 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002581
Chris Lattner7adf0762008-08-04 07:31:14 +00002582 // Get the canonical version of the element with the extra qualifiers on it.
2583 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002584 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002585 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002586
Chris Lattner7adf0762008-08-04 07:31:14 +00002587 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002588 return CanQualType::CreateUnsafe(
2589 getConstantArrayType(NewEltTy, CAT->getSize(),
2590 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002591 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002592 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002593 return CanQualType::CreateUnsafe(
2594 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002595 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002596
Douglas Gregor4619e432008-12-05 23:32:09 +00002597 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002598 return CanQualType::CreateUnsafe(
2599 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002600 DSAT->getSizeExpr() ?
2601 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002602 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002603 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002604 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002605
Chris Lattner7adf0762008-08-04 07:31:14 +00002606 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002607 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002608 VAT->getSizeExpr() ?
2609 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002610 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002611 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002612 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002613}
2614
Chandler Carruth607f38e2009-12-29 07:16:59 +00002615QualType ASTContext::getUnqualifiedArrayType(QualType T,
2616 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002617 Quals = T.getQualifiers();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002618 if (!isa<ArrayType>(T)) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002619 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002620 }
2621
Chandler Carruth607f38e2009-12-29 07:16:59 +00002622 const ArrayType *AT = cast<ArrayType>(T);
2623 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002624 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002625 if (Elt == UnqualElt)
2626 return T;
2627
2628 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2629 return getConstantArrayType(UnqualElt, CAT->getSize(),
2630 CAT->getSizeModifier(), 0);
2631 }
2632
2633 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2634 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2635 }
2636
2637 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2638 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2639 DSAT->getSizeModifier(), 0,
2640 SourceRange());
2641}
2642
John McCall847e2a12009-11-24 18:42:40 +00002643DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2644 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2645 return TD->getDeclName();
2646
2647 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2648 if (DTN->isIdentifier()) {
2649 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2650 } else {
2651 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2652 }
2653 }
2654
John McCalld28ae272009-12-02 08:04:21 +00002655 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2656 assert(Storage);
2657 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002658}
2659
Douglas Gregor6bc50582009-05-07 06:41:52 +00002660TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2661 // If this template name refers to a template, the canonical
2662 // template name merely stores the template itself.
2663 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002664 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002665
John McCalld28ae272009-12-02 08:04:21 +00002666 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002667
Douglas Gregor6bc50582009-05-07 06:41:52 +00002668 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2669 assert(DTN && "Non-dependent template names must refer to template decls.");
2670 return DTN->CanonicalTemplateName;
2671}
2672
Douglas Gregoradee3e32009-11-11 23:06:43 +00002673bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2674 X = getCanonicalTemplateName(X);
2675 Y = getCanonicalTemplateName(Y);
2676 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2677}
2678
Mike Stump11289f42009-09-09 15:08:12 +00002679TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002680ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2681 switch (Arg.getKind()) {
2682 case TemplateArgument::Null:
2683 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregora8e02e72009-07-28 23:00:59 +00002685 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002686 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002687
Douglas Gregora8e02e72009-07-28 23:00:59 +00002688 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002689 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002690
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002691 case TemplateArgument::Template:
2692 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2693
Douglas Gregora8e02e72009-07-28 23:00:59 +00002694 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002695 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002696 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregora8e02e72009-07-28 23:00:59 +00002698 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002699 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002700
Douglas Gregora8e02e72009-07-28 23:00:59 +00002701 case TemplateArgument::Pack: {
2702 // FIXME: Allocate in ASTContext
2703 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2704 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002705 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002706 AEnd = Arg.pack_end();
2707 A != AEnd; (void)++A, ++Idx)
2708 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002709
Douglas Gregora8e02e72009-07-28 23:00:59 +00002710 TemplateArgument Result;
2711 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2712 return Result;
2713 }
2714 }
2715
2716 // Silence GCC warning
2717 assert(false && "Unhandled template argument kind");
2718 return TemplateArgument();
2719}
2720
Douglas Gregor333489b2009-03-27 23:10:48 +00002721NestedNameSpecifier *
2722ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002723 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002724 return 0;
2725
2726 switch (NNS->getKind()) {
2727 case NestedNameSpecifier::Identifier:
2728 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002729 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002730 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2731 NNS->getAsIdentifier());
2732
2733 case NestedNameSpecifier::Namespace:
2734 // A namespace is canonical; build a nested-name-specifier with
2735 // this namespace and no prefix.
2736 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2737
2738 case NestedNameSpecifier::TypeSpec:
2739 case NestedNameSpecifier::TypeSpecWithTemplate: {
2740 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002741 return NestedNameSpecifier::Create(*this, 0,
2742 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002743 T.getTypePtr());
2744 }
2745
2746 case NestedNameSpecifier::Global:
2747 // The global specifier is canonical and unique.
2748 return NNS;
2749 }
2750
2751 // Required to silence a GCC warning
2752 return 0;
2753}
2754
Chris Lattner7adf0762008-08-04 07:31:14 +00002755
2756const ArrayType *ASTContext::getAsArrayType(QualType T) {
2757 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002758 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002759 // Handle the common positive case fast.
2760 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2761 return AT;
2762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
John McCall8ccfcb52009-09-24 19:53:00 +00002764 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002765 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002766 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002767 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002768
John McCall8ccfcb52009-09-24 19:53:00 +00002769 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002770 // implements C99 6.7.3p8: "If the specification of an array type includes
2771 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattner7adf0762008-08-04 07:31:14 +00002773 // If we get here, we either have type qualifiers on the type, or we have
2774 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002775 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002776
John McCall8ccfcb52009-09-24 19:53:00 +00002777 QualifierCollector Qs;
2778 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002779
Chris Lattner7adf0762008-08-04 07:31:14 +00002780 // If we have a simple case, just return now.
2781 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002782 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002783 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002784
Chris Lattner7adf0762008-08-04 07:31:14 +00002785 // Otherwise, we have an array and we have qualifiers on it. Push the
2786 // qualifiers into the array element type and return a new array type.
2787 // Get the canonical version of the element with the extra qualifiers on it.
2788 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002789 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002790
Chris Lattner7adf0762008-08-04 07:31:14 +00002791 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2792 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2793 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002794 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002795 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2796 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2797 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002798 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002799
Mike Stump11289f42009-09-09 15:08:12 +00002800 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002801 = dyn_cast<DependentSizedArrayType>(ATy))
2802 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002803 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002804 DSAT->getSizeExpr() ?
2805 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002806 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002807 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002808 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattner7adf0762008-08-04 07:31:14 +00002810 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002811 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002812 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002813 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002814 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002815 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002816 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002817}
2818
2819
Chris Lattnera21ad802008-04-02 05:18:44 +00002820/// getArrayDecayedType - Return the properly qualified result of decaying the
2821/// specified array type to a pointer. This operation is non-trivial when
2822/// handling typedefs etc. The canonical type of "T" must be an array type,
2823/// this returns a pointer to a properly qualified element of the array.
2824///
2825/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2826QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002827 // Get the element type with 'getAsArrayType' so that we don't lose any
2828 // typedefs in the element type of the array. This also handles propagation
2829 // of type qualifiers from the array type into the element type if present
2830 // (C99 6.7.3p8).
2831 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2832 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002833
Chris Lattner7adf0762008-08-04 07:31:14 +00002834 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002835
2836 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002837 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002838}
2839
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002840QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002841 QualifierCollector Qs;
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002842 while (true) {
John McCall8ccfcb52009-09-24 19:53:00 +00002843 const Type *UT = Qs.strip(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002844 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2845 QT = AT->getElementType();
Mike Stumpea086c72009-07-25 23:24:03 +00002846 } else {
John McCall8ccfcb52009-09-24 19:53:00 +00002847 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002848 }
2849 }
2850}
2851
Anders Carlsson4bf82142009-09-25 01:23:32 +00002852QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2853 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002854
Anders Carlsson4bf82142009-09-25 01:23:32 +00002855 if (const ArrayType *AT = getAsArrayType(ElemTy))
2856 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002857
Anders Carlssone0808df2008-12-21 03:44:36 +00002858 return ElemTy;
2859}
2860
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002861/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002862uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002863ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2864 uint64_t ElementCount = 1;
2865 do {
2866 ElementCount *= CA->getSize().getZExtValue();
2867 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2868 } while (CA);
2869 return ElementCount;
2870}
2871
Steve Naroff0af91202007-04-27 21:51:21 +00002872/// getFloatingRank - Return a relative rank for floating point types.
2873/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002874static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002875 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002876 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002877
John McCall9dd450b2009-09-21 23:43:11 +00002878 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2879 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002880 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002881 case BuiltinType::Float: return FloatRank;
2882 case BuiltinType::Double: return DoubleRank;
2883 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002884 }
2885}
2886
Mike Stump11289f42009-09-09 15:08:12 +00002887/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2888/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002889/// 'typeDomain' is a real floating point or complex type.
2890/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002891QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2892 QualType Domain) const {
2893 FloatingRank EltRank = getFloatingRank(Size);
2894 if (Domain->isComplexType()) {
2895 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002896 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002897 case FloatRank: return FloatComplexTy;
2898 case DoubleRank: return DoubleComplexTy;
2899 case LongDoubleRank: return LongDoubleComplexTy;
2900 }
Steve Naroff0af91202007-04-27 21:51:21 +00002901 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002902
2903 assert(Domain->isRealFloatingType() && "Unknown domain!");
2904 switch (EltRank) {
2905 default: assert(0 && "getFloatingRank(): illegal value for rank");
2906 case FloatRank: return FloatTy;
2907 case DoubleRank: return DoubleTy;
2908 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002909 }
Steve Naroffe4718892007-04-27 18:30:00 +00002910}
2911
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002912/// getFloatingTypeOrder - Compare the rank of the two specified floating
2913/// point types, ignoring the domain of the type (i.e. 'double' ==
2914/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002915/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002916int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2917 FloatingRank LHSR = getFloatingRank(LHS);
2918 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002919
Chris Lattnerb90739d2008-04-06 23:38:49 +00002920 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002921 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002922 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002923 return 1;
2924 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002925}
2926
Chris Lattner76a00cf2008-04-06 22:59:24 +00002927/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2928/// routine will assert if passed a built-in type that isn't an integer or enum,
2929/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002930unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002931 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002932 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002933 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002934
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002935 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2936 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2937
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002938 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2939 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2940
2941 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2942 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2943
Chris Lattner76a00cf2008-04-06 22:59:24 +00002944 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002945 default: assert(0 && "getIntegerRank(): not a built-in integer");
2946 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002947 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002948 case BuiltinType::Char_S:
2949 case BuiltinType::Char_U:
2950 case BuiltinType::SChar:
2951 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002952 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002953 case BuiltinType::Short:
2954 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002955 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002956 case BuiltinType::Int:
2957 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002958 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002959 case BuiltinType::Long:
2960 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002961 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002962 case BuiltinType::LongLong:
2963 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002964 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002965 case BuiltinType::Int128:
2966 case BuiltinType::UInt128:
2967 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002968 }
2969}
2970
Eli Friedman629ffb92009-08-20 04:21:42 +00002971/// \brief Whether this is a promotable bitfield reference according
2972/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2973///
2974/// \returns the type this bit-field will promote to, or NULL if no
2975/// promotion occurs.
2976QualType ASTContext::isPromotableBitField(Expr *E) {
2977 FieldDecl *Field = E->getBitField();
2978 if (!Field)
2979 return QualType();
2980
2981 QualType FT = Field->getType();
2982
2983 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2984 uint64_t BitWidth = BitWidthAP.getZExtValue();
2985 uint64_t IntSize = getTypeSize(IntTy);
2986 // GCC extension compatibility: if the bit-field size is less than or equal
2987 // to the size of int, it gets promoted no matter what its type is.
2988 // For instance, unsigned long bf : 4 gets promoted to signed int.
2989 if (BitWidth < IntSize)
2990 return IntTy;
2991
2992 if (BitWidth == IntSize)
2993 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2994
2995 // Types bigger than int are not subject to promotions, and therefore act
2996 // like the base type.
2997 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2998 // is ridiculous.
2999 return QualType();
3000}
3001
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003002/// getPromotedIntegerType - Returns the type that Promotable will
3003/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3004/// integer type.
3005QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3006 assert(!Promotable.isNull());
3007 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003008 if (const EnumType *ET = Promotable->getAs<EnumType>())
3009 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003010 if (Promotable->isSignedIntegerType())
3011 return IntTy;
3012 uint64_t PromotableSize = getTypeSize(Promotable);
3013 uint64_t IntSize = getTypeSize(IntTy);
3014 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3015 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3016}
3017
Mike Stump11289f42009-09-09 15:08:12 +00003018/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003019/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003020/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003021int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003022 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3023 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003024 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003025
Chris Lattner76a00cf2008-04-06 22:59:24 +00003026 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3027 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003028
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003029 unsigned LHSRank = getIntegerRank(LHSC);
3030 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003031
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003032 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3033 if (LHSRank == RHSRank) return 0;
3034 return LHSRank > RHSRank ? 1 : -1;
3035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003037 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3038 if (LHSUnsigned) {
3039 // If the unsigned [LHS] type is larger, return it.
3040 if (LHSRank >= RHSRank)
3041 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003042
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003043 // If the signed type can represent all values of the unsigned type, it
3044 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003045 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003046 return -1;
3047 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003048
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003049 // If the unsigned [RHS] type is larger, return it.
3050 if (RHSRank >= LHSRank)
3051 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003052
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003053 // If the signed type can represent all values of the unsigned type, it
3054 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003055 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003056 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003057}
Anders Carlsson98f07902007-08-17 05:31:46 +00003058
Anders Carlsson6d417272009-11-14 21:45:58 +00003059static RecordDecl *
3060CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3061 SourceLocation L, IdentifierInfo *Id) {
3062 if (Ctx.getLangOptions().CPlusPlus)
3063 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3064 else
3065 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3066}
3067
Mike Stump11289f42009-09-09 15:08:12 +00003068// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00003069QualType ASTContext::getCFConstantStringType() {
3070 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003071 CFConstantStringTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003072 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3073 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003074 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003075
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003076 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003077
Anders Carlsson98f07902007-08-17 05:31:46 +00003078 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003079 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003080 // int flags;
3081 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003082 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003083 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003084 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003085 FieldTypes[3] = LongTy;
3086
Anders Carlsson98f07902007-08-17 05:31:46 +00003087 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003088 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003089 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003090 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003091 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003092 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003093 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003094 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003095 }
3096
Douglas Gregord5058122010-02-11 01:19:42 +00003097 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003098 }
Mike Stump11289f42009-09-09 15:08:12 +00003099
Anders Carlsson98f07902007-08-17 05:31:46 +00003100 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003101}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003102
Douglas Gregor512b0772009-04-23 22:29:11 +00003103void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003104 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003105 assert(Rec && "Invalid CFConstantStringType");
3106 CFConstantStringTypeDecl = Rec->getDecl();
3107}
3108
Mike Stump11289f42009-09-09 15:08:12 +00003109QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003110 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003111 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003112 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3113 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003114 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003115
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003116 QualType FieldTypes[] = {
3117 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003118 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003119 getPointerType(UnsignedLongTy),
3120 getConstantArrayType(UnsignedLongTy,
3121 llvm::APInt(32, 5), ArrayType::Normal, 0)
3122 };
Mike Stump11289f42009-09-09 15:08:12 +00003123
Douglas Gregor91f84212008-12-11 16:49:14 +00003124 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003125 FieldDecl *Field = FieldDecl::Create(*this,
3126 ObjCFastEnumerationStateTypeDecl,
3127 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003128 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003129 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003130 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003131 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
Douglas Gregord5058122010-02-11 01:19:42 +00003134 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003137 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3138}
3139
Mike Stumpd0153282009-10-20 02:12:22 +00003140QualType ASTContext::getBlockDescriptorType() {
3141 if (BlockDescriptorType)
3142 return getTagDeclType(BlockDescriptorType);
3143
3144 RecordDecl *T;
3145 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003146 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3147 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003148 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003149
3150 QualType FieldTypes[] = {
3151 UnsignedLongTy,
3152 UnsignedLongTy,
3153 };
3154
3155 const char *FieldNames[] = {
3156 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003157 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003158 };
3159
3160 for (size_t i = 0; i < 2; ++i) {
3161 FieldDecl *Field = FieldDecl::Create(*this,
3162 T,
3163 SourceLocation(),
3164 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003165 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003166 /*BitWidth=*/0,
3167 /*Mutable=*/false);
3168 T->addDecl(Field);
3169 }
3170
Douglas Gregord5058122010-02-11 01:19:42 +00003171 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003172
3173 BlockDescriptorType = T;
3174
3175 return getTagDeclType(BlockDescriptorType);
3176}
3177
3178void ASTContext::setBlockDescriptorType(QualType T) {
3179 const RecordType *Rec = T->getAs<RecordType>();
3180 assert(Rec && "Invalid BlockDescriptorType");
3181 BlockDescriptorType = Rec->getDecl();
3182}
3183
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003184QualType ASTContext::getBlockDescriptorExtendedType() {
3185 if (BlockDescriptorExtendedType)
3186 return getTagDeclType(BlockDescriptorExtendedType);
3187
3188 RecordDecl *T;
3189 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003190 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3191 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003192 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003193
3194 QualType FieldTypes[] = {
3195 UnsignedLongTy,
3196 UnsignedLongTy,
3197 getPointerType(VoidPtrTy),
3198 getPointerType(VoidPtrTy)
3199 };
3200
3201 const char *FieldNames[] = {
3202 "reserved",
3203 "Size",
3204 "CopyFuncPtr",
3205 "DestroyFuncPtr"
3206 };
3207
3208 for (size_t i = 0; i < 4; ++i) {
3209 FieldDecl *Field = FieldDecl::Create(*this,
3210 T,
3211 SourceLocation(),
3212 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003213 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003214 /*BitWidth=*/0,
3215 /*Mutable=*/false);
3216 T->addDecl(Field);
3217 }
3218
Douglas Gregord5058122010-02-11 01:19:42 +00003219 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003220
3221 BlockDescriptorExtendedType = T;
3222
3223 return getTagDeclType(BlockDescriptorExtendedType);
3224}
3225
3226void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3227 const RecordType *Rec = T->getAs<RecordType>();
3228 assert(Rec && "Invalid BlockDescriptorType");
3229 BlockDescriptorExtendedType = Rec->getDecl();
3230}
3231
Mike Stump94967902009-10-21 18:16:27 +00003232bool ASTContext::BlockRequiresCopying(QualType Ty) {
3233 if (Ty->isBlockPointerType())
3234 return true;
3235 if (isObjCNSObjectType(Ty))
3236 return true;
3237 if (Ty->isObjCObjectPointerType())
3238 return true;
3239 return false;
3240}
3241
3242QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3243 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003244 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003245 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003246 // unsigned int __flags;
3247 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003248 // void *__copy_helper; // as needed
3249 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003250 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003251 // } *
3252
Mike Stump94967902009-10-21 18:16:27 +00003253 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3254
3255 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003256 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003257 llvm::SmallString<36> Name;
3258 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3259 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003260 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003261 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3262 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003263 T->startDefinition();
3264 QualType Int32Ty = IntTy;
3265 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3266 QualType FieldTypes[] = {
3267 getPointerType(VoidPtrTy),
3268 getPointerType(getTagDeclType(T)),
3269 Int32Ty,
3270 Int32Ty,
3271 getPointerType(VoidPtrTy),
3272 getPointerType(VoidPtrTy),
3273 Ty
3274 };
3275
3276 const char *FieldNames[] = {
3277 "__isa",
3278 "__forwarding",
3279 "__flags",
3280 "__size",
3281 "__copy_helper",
3282 "__destroy_helper",
3283 DeclName,
3284 };
3285
3286 for (size_t i = 0; i < 7; ++i) {
3287 if (!HasCopyAndDispose && i >=4 && i <= 5)
3288 continue;
3289 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3290 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003291 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003292 /*BitWidth=*/0, /*Mutable=*/false);
3293 T->addDecl(Field);
3294 }
3295
Douglas Gregord5058122010-02-11 01:19:42 +00003296 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003297
3298 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003299}
3300
3301
3302QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003303 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003304 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003305 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003306 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003307 llvm::SmallString<36> Name;
3308 llvm::raw_svector_ostream(Name) << "__block_literal_"
3309 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003310 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003311 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3312 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003313 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003314 QualType FieldTypes[] = {
3315 getPointerType(VoidPtrTy),
3316 IntTy,
3317 IntTy,
3318 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003319 (BlockHasCopyDispose ?
3320 getPointerType(getBlockDescriptorExtendedType()) :
3321 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003322 };
3323
3324 const char *FieldNames[] = {
3325 "__isa",
3326 "__flags",
3327 "__reserved",
3328 "__FuncPtr",
3329 "__descriptor"
3330 };
3331
3332 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003333 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003334 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003335 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003336 /*BitWidth=*/0, /*Mutable=*/false);
3337 T->addDecl(Field);
3338 }
3339
3340 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3341 const Expr *E = BlockDeclRefDecls[i];
3342 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3343 clang::IdentifierInfo *Name = 0;
3344 if (BDRE) {
3345 const ValueDecl *D = BDRE->getDecl();
3346 Name = &Idents.get(D->getName());
3347 }
3348 QualType FieldType = E->getType();
3349
3350 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003351 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3352 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003353
3354 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003355 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003356 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpd0153282009-10-20 02:12:22 +00003357 T->addDecl(Field);
3358 }
3359
Douglas Gregord5058122010-02-11 01:19:42 +00003360 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003361
3362 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003363}
3364
Douglas Gregor512b0772009-04-23 22:29:11 +00003365void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003366 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003367 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3368 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3369}
3370
Anders Carlsson18acd442007-10-29 06:33:42 +00003371// This returns true if a type has been typedefed to BOOL:
3372// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003373static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003374 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003375 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3376 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003377
Anders Carlssond8499822007-10-29 05:01:08 +00003378 return false;
3379}
3380
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003381/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003382/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003383CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003384 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003385
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003386 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003387 if (sz.isPositive() && type->isIntegralType())
3388 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003389 // Treat arrays as pointers, since that's how they're passed in.
3390 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003391 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003392 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003393}
3394
3395static inline
3396std::string charUnitsToString(const CharUnits &CU) {
3397 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003398}
3399
David Chisnall950a9512009-11-17 19:33:30 +00003400/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3401/// declaration.
3402void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3403 std::string& S) {
3404 const BlockDecl *Decl = Expr->getBlockDecl();
3405 QualType BlockTy =
3406 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3407 // Encode result type.
3408 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3409 // Compute size of all parameters.
3410 // Start with computing size of a pointer in number of bytes.
3411 // FIXME: There might(should) be a better way of doing this computation!
3412 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003413 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3414 CharUnits ParmOffset = PtrSize;
David Chisnall950a9512009-11-17 19:33:30 +00003415 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3416 E = Decl->param_end(); PI != E; ++PI) {
3417 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003418 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003419 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003420 ParmOffset += sz;
3421 }
3422 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003423 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003424 // Block pointer and offset.
3425 S += "@?0";
3426 ParmOffset = PtrSize;
3427
3428 // Argument types.
3429 ParmOffset = PtrSize;
3430 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3431 Decl->param_end(); PI != E; ++PI) {
3432 ParmVarDecl *PVDecl = *PI;
3433 QualType PType = PVDecl->getOriginalType();
3434 if (const ArrayType *AT =
3435 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3436 // Use array's original type only if it has known number of
3437 // elements.
3438 if (!isa<ConstantArrayType>(AT))
3439 PType = PVDecl->getType();
3440 } else if (PType->isFunctionType())
3441 PType = PVDecl->getType();
3442 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003443 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003444 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003445 }
3446}
3447
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003448/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003449/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003450void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003451 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003452 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003453 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003454 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003455 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003456 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003457 // Compute size of all parameters.
3458 // Start with computing size of a pointer in number of bytes.
3459 // FIXME: There might(should) be a better way of doing this computation!
3460 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003461 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003462 // The first two arguments (self and _cmd) are pointers; account for
3463 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003464 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003465 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3466 E = Decl->param_end(); PI != E; ++PI) {
3467 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003468 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003469 assert (sz.isPositive() &&
3470 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003471 ParmOffset += sz;
3472 }
Ken Dyck40775002010-01-11 17:06:35 +00003473 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003474 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003475 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003476
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003477 // Argument types.
3478 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003479 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3480 E = Decl->param_end(); PI != E; ++PI) {
3481 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003482 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003483 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003484 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3485 // Use array's original type only if it has known number of
3486 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003487 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003488 PType = PVDecl->getType();
3489 } else if (PType->isFunctionType())
3490 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003491 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003492 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003493 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003494 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003495 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003496 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003497 }
3498}
3499
Daniel Dunbar4932b362008-08-28 04:38:10 +00003500/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003501/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003502/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3503/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003504/// Property attributes are stored as a comma-delimited C string. The simple
3505/// attributes readonly and bycopy are encoded as single characters. The
3506/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3507/// encoded as single characters, followed by an identifier. Property types
3508/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003509/// these attributes are defined by the following enumeration:
3510/// @code
3511/// enum PropertyAttributes {
3512/// kPropertyReadOnly = 'R', // property is read-only.
3513/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3514/// kPropertyByref = '&', // property is a reference to the value last assigned
3515/// kPropertyDynamic = 'D', // property is dynamic
3516/// kPropertyGetter = 'G', // followed by getter selector name
3517/// kPropertySetter = 'S', // followed by setter selector name
3518/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3519/// kPropertyType = 't' // followed by old-style type encoding.
3520/// kPropertyWeak = 'W' // 'weak' property
3521/// kPropertyStrong = 'P' // property GC'able
3522/// kPropertyNonAtomic = 'N' // property non-atomic
3523/// };
3524/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003525void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003526 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003527 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003528 // Collect information from the property implementation decl(s).
3529 bool Dynamic = false;
3530 ObjCPropertyImplDecl *SynthesizePID = 0;
3531
3532 // FIXME: Duplicated code due to poor abstraction.
3533 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003534 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003535 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3536 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003537 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003538 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003539 ObjCPropertyImplDecl *PID = *i;
3540 if (PID->getPropertyDecl() == PD) {
3541 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3542 Dynamic = true;
3543 } else {
3544 SynthesizePID = PID;
3545 }
3546 }
3547 }
3548 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003549 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003550 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003551 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003552 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003553 ObjCPropertyImplDecl *PID = *i;
3554 if (PID->getPropertyDecl() == PD) {
3555 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3556 Dynamic = true;
3557 } else {
3558 SynthesizePID = PID;
3559 }
3560 }
Mike Stump11289f42009-09-09 15:08:12 +00003561 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003562 }
3563 }
3564
3565 // FIXME: This is not very efficient.
3566 S = "T";
3567
3568 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003569 // GCC has some special rules regarding encoding of properties which
3570 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003571 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003572 true /* outermost type */,
3573 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003574
3575 if (PD->isReadOnly()) {
3576 S += ",R";
3577 } else {
3578 switch (PD->getSetterKind()) {
3579 case ObjCPropertyDecl::Assign: break;
3580 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003581 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003582 }
3583 }
3584
3585 // It really isn't clear at all what this means, since properties
3586 // are "dynamic by default".
3587 if (Dynamic)
3588 S += ",D";
3589
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003590 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3591 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003592
Daniel Dunbar4932b362008-08-28 04:38:10 +00003593 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3594 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003595 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003596 }
3597
3598 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3599 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003600 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003601 }
3602
3603 if (SynthesizePID) {
3604 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3605 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003606 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003607 }
3608
3609 // FIXME: OBJCGC: weak & strong
3610}
3611
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003612/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003613/// Another legacy compatibility encoding: 32-bit longs are encoded as
3614/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003615/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3616///
3617void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003618 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003619 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003620 if (BT->getKind() == BuiltinType::ULong &&
3621 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003622 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003623 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003624 if (BT->getKind() == BuiltinType::Long &&
3625 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003626 PointeeTy = IntTy;
3627 }
3628 }
3629}
3630
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003631void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003632 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003633 // We follow the behavior of gcc, expanding structures which are
3634 // directly pointed to, and expanding embedded structures. Note that
3635 // these rules are sufficient to prevent recursive encoding of the
3636 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003637 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003638 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003639}
3640
Mike Stump11289f42009-09-09 15:08:12 +00003641static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003642 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003643 const Expr *E = FD->getBitWidth();
3644 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3645 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003646 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003647 S += 'b';
3648 S += llvm::utostr(N);
3649}
3650
Daniel Dunbar07d07852009-10-18 21:17:35 +00003651// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003652void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3653 bool ExpandPointedToStructures,
3654 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003655 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003656 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003657 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003658 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003659 if (FD && FD->isBitField())
3660 return EncodeBitField(this, S, FD);
3661 char encoding;
3662 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003663 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003664 case BuiltinType::Void: encoding = 'v'; break;
3665 case BuiltinType::Bool: encoding = 'B'; break;
3666 case BuiltinType::Char_U:
3667 case BuiltinType::UChar: encoding = 'C'; break;
3668 case BuiltinType::UShort: encoding = 'S'; break;
3669 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003670 case BuiltinType::ULong:
3671 encoding =
3672 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003673 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003674 case BuiltinType::UInt128: encoding = 'T'; break;
3675 case BuiltinType::ULongLong: encoding = 'Q'; break;
3676 case BuiltinType::Char_S:
3677 case BuiltinType::SChar: encoding = 'c'; break;
3678 case BuiltinType::Short: encoding = 's'; break;
3679 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003680 case BuiltinType::Long:
3681 encoding =
3682 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003683 break;
3684 case BuiltinType::LongLong: encoding = 'q'; break;
3685 case BuiltinType::Int128: encoding = 't'; break;
3686 case BuiltinType::Float: encoding = 'f'; break;
3687 case BuiltinType::Double: encoding = 'd'; break;
3688 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003689 }
Mike Stump11289f42009-09-09 15:08:12 +00003690
Chris Lattnere7cabb92009-07-13 00:10:46 +00003691 S += encoding;
3692 return;
3693 }
Mike Stump11289f42009-09-09 15:08:12 +00003694
John McCall9dd450b2009-09-21 23:43:11 +00003695 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003696 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003697 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003698 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003699 return;
3700 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003701
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003702 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003703 if (PT->isObjCSelType()) {
3704 S += ':';
3705 return;
3706 }
Anders Carlssond8499822007-10-29 05:01:08 +00003707 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003708
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003709 bool isReadOnly = false;
3710 // For historical/compatibility reasons, the read-only qualifier of the
3711 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3712 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003713 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003714 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003715 if (OutermostType && T.isConstQualified()) {
3716 isReadOnly = true;
3717 S += 'r';
3718 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003719 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003720 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003721 while (P->getAs<PointerType>())
3722 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003723 if (P.isConstQualified()) {
3724 isReadOnly = true;
3725 S += 'r';
3726 }
3727 }
3728 if (isReadOnly) {
3729 // Another legacy compatibility encoding. Some ObjC qualifier and type
3730 // combinations need to be rearranged.
3731 // Rewrite "in const" from "nr" to "rn"
3732 const char * s = S.c_str();
3733 int len = S.length();
3734 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3735 std::string replace = "rn";
3736 S.replace(S.end()-2, S.end(), replace);
3737 }
3738 }
Mike Stump11289f42009-09-09 15:08:12 +00003739
Anders Carlssond8499822007-10-29 05:01:08 +00003740 if (PointeeTy->isCharType()) {
3741 // char pointer types should be encoded as '*' unless it is a
3742 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003743 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003744 S += '*';
3745 return;
3746 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003747 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003748 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3749 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3750 S += '#';
3751 return;
3752 }
3753 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3754 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3755 S += '@';
3756 return;
3757 }
3758 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003759 }
Anders Carlssond8499822007-10-29 05:01:08 +00003760 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003761 getLegacyIntegralTypeEncoding(PointeeTy);
3762
Mike Stump11289f42009-09-09 15:08:12 +00003763 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003764 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003765 return;
3766 }
Mike Stump11289f42009-09-09 15:08:12 +00003767
Chris Lattnere7cabb92009-07-13 00:10:46 +00003768 if (const ArrayType *AT =
3769 // Ignore type qualifiers etc.
3770 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003771 if (isa<IncompleteArrayType>(AT)) {
3772 // Incomplete arrays are encoded as a pointer to the array element.
3773 S += '^';
3774
Mike Stump11289f42009-09-09 15:08:12 +00003775 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003776 false, ExpandStructures, FD);
3777 } else {
3778 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003779
Anders Carlssond05f44b2009-02-22 01:38:57 +00003780 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3781 S += llvm::utostr(CAT->getSize().getZExtValue());
3782 else {
3783 //Variable length arrays are encoded as a regular array with 0 elements.
3784 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3785 S += '0';
3786 }
Mike Stump11289f42009-09-09 15:08:12 +00003787
3788 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003789 false, ExpandStructures, FD);
3790 S += ']';
3791 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003792 return;
3793 }
Mike Stump11289f42009-09-09 15:08:12 +00003794
John McCall9dd450b2009-09-21 23:43:11 +00003795 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003796 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003797 return;
3798 }
Mike Stump11289f42009-09-09 15:08:12 +00003799
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003800 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003801 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003802 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003803 // Anonymous structures print as '?'
3804 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3805 S += II->getName();
3806 } else {
3807 S += '?';
3808 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003809 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003810 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003811 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3812 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003813 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003814 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003815 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003816 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003817 S += '"';
3818 }
Mike Stump11289f42009-09-09 15:08:12 +00003819
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003820 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003821 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003822 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003823 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003824 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003825 QualType qt = Field->getType();
3826 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003827 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003828 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003829 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003830 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003831 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003832 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003833 return;
3834 }
Mike Stump11289f42009-09-09 15:08:12 +00003835
Chris Lattnere7cabb92009-07-13 00:10:46 +00003836 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003837 if (FD && FD->isBitField())
3838 EncodeBitField(this, S, FD);
3839 else
3840 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003841 return;
3842 }
Mike Stump11289f42009-09-09 15:08:12 +00003843
Chris Lattnere7cabb92009-07-13 00:10:46 +00003844 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003845 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003846 return;
3847 }
Mike Stump11289f42009-09-09 15:08:12 +00003848
John McCall8ccfcb52009-09-24 19:53:00 +00003849 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003850 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003851 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003852 S += '{';
3853 const IdentifierInfo *II = OI->getIdentifier();
3854 S += II->getName();
3855 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003856 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003857 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003858 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003859 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003860 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003861 RecFields[i]);
3862 else
Mike Stump11289f42009-09-09 15:08:12 +00003863 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003864 FD);
3865 }
3866 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003867 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003868 }
Mike Stump11289f42009-09-09 15:08:12 +00003869
John McCall9dd450b2009-09-21 23:43:11 +00003870 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003871 if (OPT->isObjCIdType()) {
3872 S += '@';
3873 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003874 }
Mike Stump11289f42009-09-09 15:08:12 +00003875
Steve Narofff0c86112009-10-28 22:03:49 +00003876 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3877 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3878 // Since this is a binary compatibility issue, need to consult with runtime
3879 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003880 S += '#';
3881 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003882 }
Mike Stump11289f42009-09-09 15:08:12 +00003883
Chris Lattnere7cabb92009-07-13 00:10:46 +00003884 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003885 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003886 ExpandPointedToStructures,
3887 ExpandStructures, FD);
3888 if (FD || EncodingProperty) {
3889 // Note that we do extended encoding of protocol qualifer list
3890 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003891 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003892 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3893 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003894 S += '<';
3895 S += (*I)->getNameAsString();
3896 S += '>';
3897 }
3898 S += '"';
3899 }
3900 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003901 }
Mike Stump11289f42009-09-09 15:08:12 +00003902
Chris Lattnere7cabb92009-07-13 00:10:46 +00003903 QualType PointeeTy = OPT->getPointeeType();
3904 if (!EncodingProperty &&
3905 isa<TypedefType>(PointeeTy.getTypePtr())) {
3906 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003907 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003908 // {...};
3909 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003910 getObjCEncodingForTypeImpl(PointeeTy, S,
3911 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003912 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003913 return;
3914 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003915
3916 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003917 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003918 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003919 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003920 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3921 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003922 S += '<';
3923 S += (*I)->getNameAsString();
3924 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003925 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003926 S += '"';
3927 }
3928 return;
3929 }
Mike Stump11289f42009-09-09 15:08:12 +00003930
Chris Lattnere7cabb92009-07-13 00:10:46 +00003931 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003932}
3933
Mike Stump11289f42009-09-09 15:08:12 +00003934void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003935 std::string& S) const {
3936 if (QT & Decl::OBJC_TQ_In)
3937 S += 'n';
3938 if (QT & Decl::OBJC_TQ_Inout)
3939 S += 'N';
3940 if (QT & Decl::OBJC_TQ_Out)
3941 S += 'o';
3942 if (QT & Decl::OBJC_TQ_Bycopy)
3943 S += 'O';
3944 if (QT & Decl::OBJC_TQ_Byref)
3945 S += 'R';
3946 if (QT & Decl::OBJC_TQ_Oneway)
3947 S += 'V';
3948}
3949
Chris Lattnere7cabb92009-07-13 00:10:46 +00003950void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003951 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003952
Anders Carlsson87c149b2007-10-11 01:00:40 +00003953 BuiltinVaListType = T;
3954}
3955
Chris Lattnere7cabb92009-07-13 00:10:46 +00003956void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003957 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003958}
3959
Chris Lattnere7cabb92009-07-13 00:10:46 +00003960void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003961 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003962}
3963
Chris Lattnere7cabb92009-07-13 00:10:46 +00003964void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003965 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003966}
3967
Chris Lattnere7cabb92009-07-13 00:10:46 +00003968void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003969 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003970}
3971
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003972void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003973 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003974 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003975
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003976 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003977}
3978
John McCalld28ae272009-12-02 08:04:21 +00003979/// \brief Retrieve the template name that corresponds to a non-empty
3980/// lookup.
John McCallad371252010-01-20 00:46:10 +00003981TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3982 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003983 unsigned size = End - Begin;
3984 assert(size > 1 && "set is not overloaded!");
3985
3986 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3987 size * sizeof(FunctionTemplateDecl*));
3988 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3989
3990 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003991 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003992 NamedDecl *D = *I;
3993 assert(isa<FunctionTemplateDecl>(D) ||
3994 (isa<UsingShadowDecl>(D) &&
3995 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3996 *Storage++ = D;
3997 }
3998
3999 return TemplateName(OT);
4000}
4001
Douglas Gregordc572a32009-03-30 22:58:21 +00004002/// \brief Retrieve the template name that represents a qualified
4003/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00004004TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004005 bool TemplateKeyword,
4006 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004007 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004008 llvm::FoldingSetNodeID ID;
4009 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4010
4011 void *InsertPos = 0;
4012 QualifiedTemplateName *QTN =
4013 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4014 if (!QTN) {
4015 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4016 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4017 }
4018
4019 return TemplateName(QTN);
4020}
4021
4022/// \brief Retrieve the template name that represents a dependent
4023/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004024TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004025 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004026 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004027 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004028
4029 llvm::FoldingSetNodeID ID;
4030 DependentTemplateName::Profile(ID, NNS, Name);
4031
4032 void *InsertPos = 0;
4033 DependentTemplateName *QTN =
4034 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4035
4036 if (QTN)
4037 return TemplateName(QTN);
4038
4039 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4040 if (CanonNNS == NNS) {
4041 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4042 } else {
4043 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4044 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004045 DependentTemplateName *CheckQTN =
4046 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4047 assert(!CheckQTN && "Dependent type name canonicalization broken");
4048 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004049 }
4050
4051 DependentTemplateNames.InsertNode(QTN, InsertPos);
4052 return TemplateName(QTN);
4053}
4054
Douglas Gregor71395fa2009-11-04 00:56:37 +00004055/// \brief Retrieve the template name that represents a dependent
4056/// template name such as \c MetaFun::template operator+.
4057TemplateName
4058ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4059 OverloadedOperatorKind Operator) {
4060 assert((!NNS || NNS->isDependent()) &&
4061 "Nested name specifier must be dependent");
4062
4063 llvm::FoldingSetNodeID ID;
4064 DependentTemplateName::Profile(ID, NNS, Operator);
4065
4066 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004067 DependentTemplateName *QTN
4068 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004069
4070 if (QTN)
4071 return TemplateName(QTN);
4072
4073 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4074 if (CanonNNS == NNS) {
4075 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4076 } else {
4077 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4078 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004079
4080 DependentTemplateName *CheckQTN
4081 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4082 assert(!CheckQTN && "Dependent template name canonicalization broken");
4083 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004084 }
4085
4086 DependentTemplateNames.InsertNode(QTN, InsertPos);
4087 return TemplateName(QTN);
4088}
4089
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004090/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004091/// TargetInfo, produce the corresponding type. The unsigned @p Type
4092/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004093CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004094 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004095 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004096 case TargetInfo::SignedShort: return ShortTy;
4097 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4098 case TargetInfo::SignedInt: return IntTy;
4099 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4100 case TargetInfo::SignedLong: return LongTy;
4101 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4102 case TargetInfo::SignedLongLong: return LongLongTy;
4103 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4104 }
4105
4106 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004107 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004108}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004109
4110//===----------------------------------------------------------------------===//
4111// Type Predicates.
4112//===----------------------------------------------------------------------===//
4113
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004114/// isObjCNSObjectType - Return true if this is an NSObject object using
4115/// NSObject attribute on a c-style pointer type.
4116/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004117/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004118///
4119bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4120 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4121 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004122 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004123 return true;
4124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004126}
4127
Fariborz Jahanian96207692009-02-18 21:49:28 +00004128/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4129/// garbage collection attribute.
4130///
John McCall8ccfcb52009-09-24 19:53:00 +00004131Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4132 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004133 if (getLangOptions().ObjC1 &&
4134 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004135 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004136 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004137 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004138 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004139 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004140 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004141 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004142 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004143 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004144 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004145 // Non-pointers have none gc'able attribute regardless of the attribute
4146 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004147 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004148 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004149 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004150 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004151}
4152
Chris Lattner49af6a42008-04-07 06:51:04 +00004153//===----------------------------------------------------------------------===//
4154// Type Compatibility Testing
4155//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004156
Mike Stump11289f42009-09-09 15:08:12 +00004157/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004158/// compatible.
4159static bool areCompatVectorTypes(const VectorType *LHS,
4160 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004161 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004162 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004163 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004164}
4165
Steve Naroff8e6aee52009-07-23 01:01:38 +00004166//===----------------------------------------------------------------------===//
4167// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4168//===----------------------------------------------------------------------===//
4169
4170/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4171/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004172bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4173 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004174 if (lProto == rProto)
4175 return true;
4176 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4177 E = rProto->protocol_end(); PI != E; ++PI)
4178 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4179 return true;
4180 return false;
4181}
4182
Steve Naroff8e6aee52009-07-23 01:01:38 +00004183/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4184/// return true if lhs's protocols conform to rhs's protocol; false
4185/// otherwise.
4186bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4187 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4188 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4189 return false;
4190}
4191
4192/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4193/// ObjCQualifiedIDType.
4194bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4195 bool compare) {
4196 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004197 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004198 lhs->isObjCIdType() || lhs->isObjCClassType())
4199 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004200 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004201 rhs->isObjCIdType() || rhs->isObjCClassType())
4202 return true;
4203
4204 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004205 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004206
Steve Naroff8e6aee52009-07-23 01:01:38 +00004207 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004208
Steve Naroff8e6aee52009-07-23 01:01:38 +00004209 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004210 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004211 // make sure we check the class hierarchy.
4212 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4213 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4214 E = lhsQID->qual_end(); I != E; ++I) {
4215 // when comparing an id<P> on lhs with a static type on rhs,
4216 // see if static class implements all of id's protocols, directly or
4217 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004218 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004219 return false;
4220 }
4221 }
4222 // If there are no qualifiers and no interface, we have an 'id'.
4223 return true;
4224 }
Mike Stump11289f42009-09-09 15:08:12 +00004225 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004226 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4227 E = lhsQID->qual_end(); I != E; ++I) {
4228 ObjCProtocolDecl *lhsProto = *I;
4229 bool match = false;
4230
4231 // when comparing an id<P> on lhs with a static type on rhs,
4232 // see if static class implements all of id's protocols, directly or
4233 // through its super class and categories.
4234 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4235 E = rhsOPT->qual_end(); J != E; ++J) {
4236 ObjCProtocolDecl *rhsProto = *J;
4237 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4238 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4239 match = true;
4240 break;
4241 }
4242 }
Mike Stump11289f42009-09-09 15:08:12 +00004243 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004244 // make sure we check the class hierarchy.
4245 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4246 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4247 E = lhsQID->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 Jahanian3f8917a2009-08-11 22:02:25 +00004251 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004252 match = true;
4253 break;
4254 }
4255 }
4256 }
4257 if (!match)
4258 return false;
4259 }
Mike Stump11289f42009-09-09 15:08:12 +00004260
Steve Naroff8e6aee52009-07-23 01:01:38 +00004261 return true;
4262 }
Mike Stump11289f42009-09-09 15:08:12 +00004263
Steve Naroff8e6aee52009-07-23 01:01:38 +00004264 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4265 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4266
Mike Stump11289f42009-09-09 15:08:12 +00004267 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004268 lhs->getAsObjCInterfacePointerType()) {
4269 if (lhsOPT->qual_empty()) {
4270 bool match = false;
4271 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4272 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4273 E = rhsQID->qual_end(); I != E; ++I) {
4274 // when comparing an id<P> on lhs with a static type on rhs,
4275 // see if static class implements all of id's protocols, directly or
4276 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004277 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004278 match = true;
4279 break;
4280 }
4281 }
4282 if (!match)
4283 return false;
4284 }
4285 return true;
4286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004288 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4289 E = lhsOPT->qual_end(); I != E; ++I) {
4290 ObjCProtocolDecl *lhsProto = *I;
4291 bool match = false;
4292
4293 // when comparing an id<P> on lhs with a static type on rhs,
4294 // see if static class implements all of id's protocols, directly or
4295 // through its super class and categories.
4296 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4297 E = rhsQID->qual_end(); J != E; ++J) {
4298 ObjCProtocolDecl *rhsProto = *J;
4299 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4300 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4301 match = true;
4302 break;
4303 }
4304 }
4305 if (!match)
4306 return false;
4307 }
4308 return true;
4309 }
4310 return false;
4311}
4312
Eli Friedman47f77112008-08-22 00:56:42 +00004313/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004314/// compatible for assignment from RHS to LHS. This handles validation of any
4315/// protocol qualifiers on the LHS or RHS.
4316///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004317bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4318 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004319 // If either type represents the built-in 'id' or 'Class' types, return true.
4320 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004321 return true;
4322
Steve Naroff8e6aee52009-07-23 01:01:38 +00004323 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00004324 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4325 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004326 false);
4327
Steve Naroff7cae42b2009-07-10 23:34:53 +00004328 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4329 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff8e6aee52009-07-23 01:01:38 +00004330 if (LHS && RHS) // We have 2 user-defined types.
4331 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004332
Steve Naroff8e6aee52009-07-23 01:01:38 +00004333 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004334}
4335
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004336/// getIntersectionOfProtocols - This routine finds the intersection of set
4337/// of protocols inherited from two distinct objective-c pointer objects.
4338/// It is used to build composite qualifier list of the composite type of
4339/// the conditional expression involving two objective-c pointer objects.
4340static
4341void getIntersectionOfProtocols(ASTContext &Context,
4342 const ObjCObjectPointerType *LHSOPT,
4343 const ObjCObjectPointerType *RHSOPT,
4344 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4345
4346 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4347 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4348
4349 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4350 unsigned LHSNumProtocols = LHS->getNumProtocols();
4351 if (LHSNumProtocols > 0)
4352 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4353 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004354 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4355 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004356 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4357 LHSInheritedProtocols.end());
4358 }
4359
4360 unsigned RHSNumProtocols = RHS->getNumProtocols();
4361 if (RHSNumProtocols > 0) {
4362 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4363 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4364 if (InheritedProtocolSet.count(RHSProtocols[i]))
4365 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4366 }
4367 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004368 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004369 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004370 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4371 RHSInheritedProtocols.begin(),
4372 E = RHSInheritedProtocols.end(); I != E; ++I)
4373 if (InheritedProtocolSet.count((*I)))
4374 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004375 }
4376}
4377
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004378/// areCommonBaseCompatible - Returns common base class of the two classes if
4379/// one found. Note that this is O'2 algorithm. But it will be called as the
4380/// last type comparison in a ?-exp of ObjC pointer types before a
4381/// warning is issued. So, its invokation is extremely rare.
4382QualType ASTContext::areCommonBaseCompatible(
4383 const ObjCObjectPointerType *LHSOPT,
4384 const ObjCObjectPointerType *RHSOPT) {
4385 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4386 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4387 if (!LHS || !RHS)
4388 return QualType();
4389
4390 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4391 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4392 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004393 if (canAssignObjCInterfaces(LHS, RHS)) {
4394 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4395 getIntersectionOfProtocols(*this,
4396 LHSOPT, RHSOPT, IntersectionOfProtocols);
4397 if (IntersectionOfProtocols.empty())
4398 LHSTy = getObjCObjectPointerType(LHSTy);
4399 else
4400 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4401 IntersectionOfProtocols.size());
4402 return LHSTy;
4403 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004404 }
4405
4406 return QualType();
4407}
4408
Eli Friedman47f77112008-08-22 00:56:42 +00004409bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4410 const ObjCInterfaceType *RHS) {
Chris Lattner49af6a42008-04-07 06:51:04 +00004411 // Verify that the base decls are compatible: the RHS must be a subclass of
4412 // the LHS.
4413 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4414 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004415
Chris Lattner49af6a42008-04-07 06:51:04 +00004416 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4417 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004418 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004419 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004420
Chris Lattner49af6a42008-04-07 06:51:04 +00004421 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4422 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004423 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004424 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004425
Steve Naroffc277ad12009-07-18 15:33:26 +00004426 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4427 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004428 LHSPI != LHSPE; LHSPI++) {
4429 bool RHSImplementsProtocol = false;
4430
4431 // If the RHS doesn't implement the protocol on the left, the types
4432 // are incompatible.
Steve Naroffc277ad12009-07-18 15:33:26 +00004433 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004434 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004435 RHSPI != RHSPE; RHSPI++) {
4436 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004437 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004438 break;
4439 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004440 }
4441 // FIXME: For better diagnostics, consider passing back the protocol name.
4442 if (!RHSImplementsProtocol)
4443 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004444 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004445 // The RHS implements all protocols listed on the LHS.
4446 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004447}
4448
Steve Naroffb7605152009-02-12 17:52:19 +00004449bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4450 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004451 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4452 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004453
Steve Naroff7cae42b2009-07-10 23:34:53 +00004454 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004455 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004456
4457 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4458 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004459}
4460
Mike Stump11289f42009-09-09 15:08:12 +00004461/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004462/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004463/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004464/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004465bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004466 if (getLangOptions().CPlusPlus)
4467 return hasSameType(LHS, RHS);
4468
Eli Friedman47f77112008-08-22 00:56:42 +00004469 return !mergeTypes(LHS, RHS).isNull();
4470}
4471
4472QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall9dd450b2009-09-21 23:43:11 +00004473 const FunctionType *lbase = lhs->getAs<FunctionType>();
4474 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004475 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4476 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004477 bool allLTypes = true;
4478 bool allRTypes = true;
4479
4480 // Check return type
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004481 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004482 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004483 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004484 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004485 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004486 allRTypes = false;
Mike Stumpea086c72009-07-25 23:24:03 +00004487 // FIXME: double check this
Mike Stump8c5d7992009-07-25 21:26:53 +00004488 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4489 if (NoReturn != lbase->getNoReturnAttr())
4490 allLTypes = false;
4491 if (NoReturn != rbase->getNoReturnAttr())
4492 allRTypes = false;
Douglas Gregor8c940862010-01-18 17:14:39 +00004493 CallingConv lcc = lbase->getCallConv();
4494 CallingConv rcc = rbase->getCallConv();
4495 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004496 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004497 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004498
Eli Friedman47f77112008-08-22 00:56:42 +00004499 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004500 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4501 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004502 unsigned lproto_nargs = lproto->getNumArgs();
4503 unsigned rproto_nargs = rproto->getNumArgs();
4504
4505 // Compatible functions must have the same number of arguments
4506 if (lproto_nargs != rproto_nargs)
4507 return QualType();
4508
4509 // Variadic and non-variadic functions aren't compatible
4510 if (lproto->isVariadic() != rproto->isVariadic())
4511 return QualType();
4512
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004513 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4514 return QualType();
4515
Eli Friedman47f77112008-08-22 00:56:42 +00004516 // Check argument compatibility
4517 llvm::SmallVector<QualType, 10> types;
4518 for (unsigned i = 0; i < lproto_nargs; i++) {
4519 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4520 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4521 QualType argtype = mergeTypes(largtype, rargtype);
4522 if (argtype.isNull()) return QualType();
4523 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004524 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4525 allLTypes = false;
4526 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4527 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004528 }
4529 if (allLTypes) return lhs;
4530 if (allRTypes) return rhs;
4531 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004532 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor8870a492010-02-12 17:17:28 +00004533 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004534 }
4535
4536 if (lproto) allRTypes = false;
4537 if (rproto) allLTypes = false;
4538
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004539 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004540 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004541 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004542 if (proto->isVariadic()) return QualType();
4543 // Check that the types are compatible with the types that
4544 // would result from default argument promotions (C99 6.7.5.3p15).
4545 // The only types actually affected are promotable integer
4546 // types and floats, which would be passed as a different
4547 // type depending on whether the prototype is visible.
4548 unsigned proto_nargs = proto->getNumArgs();
4549 for (unsigned i = 0; i < proto_nargs; ++i) {
4550 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004551
4552 // Look at the promotion type of enum types, since that is the type used
4553 // to pass enum values.
4554 if (const EnumType *Enum = argTy->getAs<EnumType>())
4555 argTy = Enum->getDecl()->getPromotionType();
4556
Eli Friedman47f77112008-08-22 00:56:42 +00004557 if (argTy->isPromotableIntegerType() ||
4558 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4559 return QualType();
4560 }
4561
4562 if (allLTypes) return lhs;
4563 if (allRTypes) return rhs;
4564 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004565 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004566 proto->getTypeQuals(),
4567 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004568 }
4569
4570 if (allLTypes) return lhs;
4571 if (allRTypes) return rhs;
Douglas Gregor8c940862010-01-18 17:14:39 +00004572 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004573}
4574
4575QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004576 // C++ [expr]: If an expression initially has the type "reference to T", the
4577 // type is adjusted to "T" prior to any further analysis, the expression
4578 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004579 // expression is an lvalue unless the reference is an rvalue reference and
4580 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004581 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4582 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4583
Eli Friedman47f77112008-08-22 00:56:42 +00004584 QualType LHSCan = getCanonicalType(LHS),
4585 RHSCan = getCanonicalType(RHS);
4586
4587 // If two types are identical, they are compatible.
4588 if (LHSCan == RHSCan)
4589 return LHS;
4590
John McCall8ccfcb52009-09-24 19:53:00 +00004591 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004592 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4593 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004594 if (LQuals != RQuals) {
4595 // If any of these qualifiers are different, we have a type
4596 // mismatch.
4597 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4598 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4599 return QualType();
4600
4601 // Exactly one GC qualifier difference is allowed: __strong is
4602 // okay if the other type has no GC qualifier but is an Objective
4603 // C object pointer (i.e. implicitly strong by default). We fix
4604 // this by pretending that the unqualified type was actually
4605 // qualified __strong.
4606 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4607 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4608 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4609
4610 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4611 return QualType();
4612
4613 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4614 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4615 }
4616 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4617 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4618 }
Eli Friedman47f77112008-08-22 00:56:42 +00004619 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004620 }
4621
4622 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004623
Eli Friedmandcca6332009-06-01 01:22:52 +00004624 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4625 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004626
Chris Lattnerfd652912008-01-14 05:45:46 +00004627 // We want to consider the two function types to be the same for these
4628 // comparisons, just force one to the other.
4629 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4630 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004631
4632 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004633 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4634 LHSClass = Type::ConstantArray;
4635 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4636 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004637
Nate Begemance4d7fc2008-04-18 23:10:10 +00004638 // Canonicalize ExtVector -> Vector.
4639 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4640 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004641
Chris Lattner95554662008-04-07 05:43:21 +00004642 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004643 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004644 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004645 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004646 // Compatibility is based on the underlying type, not the promotion
4647 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004648 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004649 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4650 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004651 }
John McCall9dd450b2009-09-21 23:43:11 +00004652 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004653 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4654 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004655 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004656
Eli Friedman47f77112008-08-22 00:56:42 +00004657 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004658 }
Eli Friedman47f77112008-08-22 00:56:42 +00004659
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004660 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004661 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004662#define TYPE(Class, Base)
4663#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004664#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004665#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4666#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4667#include "clang/AST/TypeNodes.def"
4668 assert(false && "Non-canonical and dependent types shouldn't get here");
4669 return QualType();
4670
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004671 case Type::LValueReference:
4672 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004673 case Type::MemberPointer:
4674 assert(false && "C++ should never be in mergeTypes");
4675 return QualType();
4676
4677 case Type::IncompleteArray:
4678 case Type::VariableArray:
4679 case Type::FunctionProto:
4680 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004681 assert(false && "Types are eliminated above");
4682 return QualType();
4683
Chris Lattnerfd652912008-01-14 05:45:46 +00004684 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004685 {
4686 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004687 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4688 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004689 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4690 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004691 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004692 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004693 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004694 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004695 return getPointerType(ResultType);
4696 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004697 case Type::BlockPointer:
4698 {
4699 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004700 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4701 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroff68e167d2008-12-10 17:49:55 +00004702 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4703 if (ResultType.isNull()) return QualType();
4704 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4705 return LHS;
4706 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4707 return RHS;
4708 return getBlockPointerType(ResultType);
4709 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004710 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004711 {
4712 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4713 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4714 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4715 return QualType();
4716
4717 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4718 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4719 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4720 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004721 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4722 return LHS;
4723 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4724 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004725 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4726 ArrayType::ArraySizeModifier(), 0);
4727 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4728 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004729 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4730 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004731 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4732 return LHS;
4733 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4734 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004735 if (LVAT) {
4736 // FIXME: This isn't correct! But tricky to implement because
4737 // the array's size has to be the size of LHS, but the type
4738 // has to be different.
4739 return LHS;
4740 }
4741 if (RVAT) {
4742 // FIXME: This isn't correct! But tricky to implement because
4743 // the array's size has to be the size of RHS, but the type
4744 // has to be different.
4745 return RHS;
4746 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004747 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4748 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004749 return getIncompleteArrayType(ResultType,
4750 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004751 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004752 case Type::FunctionNoProto:
Eli Friedman47f77112008-08-22 00:56:42 +00004753 return mergeFunctionTypes(LHS, RHS);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004754 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004755 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004756 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004757 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004758 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004759 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004760 case Type::Complex:
4761 // Distinct complex types are incompatible.
4762 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004763 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004764 // FIXME: The merged type should be an ExtVector!
John McCall9dd450b2009-09-21 23:43:11 +00004765 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004766 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004767 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004768 case Type::ObjCInterface: {
Steve Naroff7a7814c2009-02-21 16:18:07 +00004769 // Check if the interfaces are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004770 // FIXME: This should be type compatibility, e.g. whether
4771 // "LHS x; RHS x;" at global scope is legal.
John McCall9dd450b2009-09-21 23:43:11 +00004772 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4773 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff7a7814c2009-02-21 16:18:07 +00004774 if (LHSIface && RHSIface &&
4775 canAssignObjCInterfaces(LHSIface, RHSIface))
4776 return LHS;
4777
Eli Friedman47f77112008-08-22 00:56:42 +00004778 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004779 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004780 case Type::ObjCObjectPointer: {
John McCall9dd450b2009-09-21 23:43:11 +00004781 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4782 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004783 return LHS;
4784
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004785 return QualType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004786 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004787 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004788
4789 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004790}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004791
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004792//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004793// Integer Predicates
4794//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004795
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004796unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004797 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004798 return 1;
John McCall56774992009-12-09 09:09:27 +00004799 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004800 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004801 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004802 return (unsigned)getTypeSize(T);
4803}
4804
4805QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4806 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004807
4808 // Turn <4 x signed int> -> <4 x unsigned int>
4809 if (const VectorType *VTy = T->getAs<VectorType>())
4810 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004811 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004812
4813 // For enums, we return the unsigned version of the base type.
4814 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004815 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004816
4817 const BuiltinType *BTy = T->getAs<BuiltinType>();
4818 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004819 switch (BTy->getKind()) {
4820 case BuiltinType::Char_S:
4821 case BuiltinType::SChar:
4822 return UnsignedCharTy;
4823 case BuiltinType::Short:
4824 return UnsignedShortTy;
4825 case BuiltinType::Int:
4826 return UnsignedIntTy;
4827 case BuiltinType::Long:
4828 return UnsignedLongTy;
4829 case BuiltinType::LongLong:
4830 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004831 case BuiltinType::Int128:
4832 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004833 default:
4834 assert(0 && "Unexpected signed integer type");
4835 return QualType();
4836 }
4837}
4838
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004839ExternalASTSource::~ExternalASTSource() { }
4840
4841void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004842
4843
4844//===----------------------------------------------------------------------===//
4845// Builtin Type Computation
4846//===----------------------------------------------------------------------===//
4847
4848/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4849/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004850static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004851 ASTContext::GetBuiltinTypeError &Error,
4852 bool AllowTypeModifiers = true) {
4853 // Modifiers.
4854 int HowLong = 0;
4855 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004856
Chris Lattnerecd79c62009-06-14 00:45:47 +00004857 // Read the modifiers first.
4858 bool Done = false;
4859 while (!Done) {
4860 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004861 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004862 case 'S':
4863 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4864 assert(!Signed && "Can't use 'S' modifier multiple times!");
4865 Signed = true;
4866 break;
4867 case 'U':
4868 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4869 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4870 Unsigned = true;
4871 break;
4872 case 'L':
4873 assert(HowLong <= 2 && "Can't have LLLL modifier");
4874 ++HowLong;
4875 break;
4876 }
4877 }
4878
4879 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004880
Chris Lattnerecd79c62009-06-14 00:45:47 +00004881 // Read the base type.
4882 switch (*Str++) {
4883 default: assert(0 && "Unknown builtin type letter!");
4884 case 'v':
4885 assert(HowLong == 0 && !Signed && !Unsigned &&
4886 "Bad modifiers used with 'v'!");
4887 Type = Context.VoidTy;
4888 break;
4889 case 'f':
4890 assert(HowLong == 0 && !Signed && !Unsigned &&
4891 "Bad modifiers used with 'f'!");
4892 Type = Context.FloatTy;
4893 break;
4894 case 'd':
4895 assert(HowLong < 2 && !Signed && !Unsigned &&
4896 "Bad modifiers used with 'd'!");
4897 if (HowLong)
4898 Type = Context.LongDoubleTy;
4899 else
4900 Type = Context.DoubleTy;
4901 break;
4902 case 's':
4903 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4904 if (Unsigned)
4905 Type = Context.UnsignedShortTy;
4906 else
4907 Type = Context.ShortTy;
4908 break;
4909 case 'i':
4910 if (HowLong == 3)
4911 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4912 else if (HowLong == 2)
4913 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4914 else if (HowLong == 1)
4915 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4916 else
4917 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4918 break;
4919 case 'c':
4920 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4921 if (Signed)
4922 Type = Context.SignedCharTy;
4923 else if (Unsigned)
4924 Type = Context.UnsignedCharTy;
4925 else
4926 Type = Context.CharTy;
4927 break;
4928 case 'b': // boolean
4929 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4930 Type = Context.BoolTy;
4931 break;
4932 case 'z': // size_t.
4933 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4934 Type = Context.getSizeType();
4935 break;
4936 case 'F':
4937 Type = Context.getCFConstantStringType();
4938 break;
4939 case 'a':
4940 Type = Context.getBuiltinVaListType();
4941 assert(!Type.isNull() && "builtin va list type not initialized!");
4942 break;
4943 case 'A':
4944 // This is a "reference" to a va_list; however, what exactly
4945 // this means depends on how va_list is defined. There are two
4946 // different kinds of va_list: ones passed by value, and ones
4947 // passed by reference. An example of a by-value va_list is
4948 // x86, where va_list is a char*. An example of by-ref va_list
4949 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4950 // we want this argument to be a char*&; for x86-64, we want
4951 // it to be a __va_list_tag*.
4952 Type = Context.getBuiltinVaListType();
4953 assert(!Type.isNull() && "builtin va list type not initialized!");
4954 if (Type->isArrayType()) {
4955 Type = Context.getArrayDecayedType(Type);
4956 } else {
4957 Type = Context.getLValueReferenceType(Type);
4958 }
4959 break;
4960 case 'V': {
4961 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004962 unsigned NumElements = strtoul(Str, &End, 10);
4963 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004964
Chris Lattnerecd79c62009-06-14 00:45:47 +00004965 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004966
Chris Lattnerecd79c62009-06-14 00:45:47 +00004967 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004968 // FIXME: Don't know what to do about AltiVec.
4969 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004970 break;
4971 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004972 case 'X': {
4973 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4974 Type = Context.getComplexType(ElementType);
4975 break;
4976 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004977 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004978 Type = Context.getFILEType();
4979 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004980 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004981 return QualType();
4982 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004983 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004984 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004985 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004986 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004987 else
4988 Type = Context.getjmp_bufType();
4989
Mike Stump2adb4da2009-07-28 23:47:15 +00004990 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004991 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004992 return QualType();
4993 }
4994 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004995 }
Mike Stump11289f42009-09-09 15:08:12 +00004996
Chris Lattnerecd79c62009-06-14 00:45:47 +00004997 if (!AllowTypeModifiers)
4998 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004999
Chris Lattnerecd79c62009-06-14 00:45:47 +00005000 Done = false;
5001 while (!Done) {
5002 switch (*Str++) {
5003 default: Done = true; --Str; break;
5004 case '*':
5005 Type = Context.getPointerType(Type);
5006 break;
5007 case '&':
5008 Type = Context.getLValueReferenceType(Type);
5009 break;
5010 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5011 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005012 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005013 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005014 case 'D':
5015 Type = Context.getVolatileType(Type);
5016 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005017 }
5018 }
Mike Stump11289f42009-09-09 15:08:12 +00005019
Chris Lattnerecd79c62009-06-14 00:45:47 +00005020 return Type;
5021}
5022
5023/// GetBuiltinType - Return the type for the specified builtin.
5024QualType ASTContext::GetBuiltinType(unsigned id,
5025 GetBuiltinTypeError &Error) {
5026 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Chris Lattnerecd79c62009-06-14 00:45:47 +00005028 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005029
Chris Lattnerecd79c62009-06-14 00:45:47 +00005030 Error = GE_None;
5031 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5032 if (Error != GE_None)
5033 return QualType();
5034 while (TypeStr[0] && TypeStr[0] != '.') {
5035 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5036 if (Error != GE_None)
5037 return QualType();
5038
5039 // Do array -> pointer decay. The builtin should use the decayed type.
5040 if (Ty->isArrayType())
5041 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005042
Chris Lattnerecd79c62009-06-14 00:45:47 +00005043 ArgTypes.push_back(Ty);
5044 }
5045
5046 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5047 "'.' should only occur at end of builtin type list!");
5048
5049 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5050 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5051 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005052
5053 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005054 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005055 TypeStr[0] == '.', 0, false, false, 0, 0,
5056 false, CC_Default);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005057}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005058
5059QualType
5060ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5061 // Perform the usual unary conversions. We do this early so that
5062 // integral promotions to "int" can allow us to exit early, in the
5063 // lhs == rhs check. Also, for conversion purposes, we ignore any
5064 // qualifiers. For example, "const float" and "float" are
5065 // equivalent.
5066 if (lhs->isPromotableIntegerType())
5067 lhs = getPromotedIntegerType(lhs);
5068 else
5069 lhs = lhs.getUnqualifiedType();
5070 if (rhs->isPromotableIntegerType())
5071 rhs = getPromotedIntegerType(rhs);
5072 else
5073 rhs = rhs.getUnqualifiedType();
5074
5075 // If both types are identical, no conversion is needed.
5076 if (lhs == rhs)
5077 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005078
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005079 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5080 // The caller can deal with this (e.g. pointer + int).
5081 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5082 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005083
5084 // At this point, we have two different arithmetic types.
5085
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005086 // Handle complex types first (C99 6.3.1.8p1).
5087 if (lhs->isComplexType() || rhs->isComplexType()) {
5088 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005089 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005090 // convert the rhs to the lhs complex type.
5091 return lhs;
5092 }
Mike Stump11289f42009-09-09 15:08:12 +00005093 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005094 // convert the lhs to the rhs complex type.
5095 return rhs;
5096 }
5097 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005098 // When both operands are complex, the shorter operand is converted to the
5099 // type of the longer, and that is the type of the result. This corresponds
5100 // to what is done when combining two real floating-point operands.
5101 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005102 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005103 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005104 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005105 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005106 // "double _Complex" is promoted to "long double _Complex".
5107 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005108
5109 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005110 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005111 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005112 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005113 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005114 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5115 // domains match. This is a requirement for our implementation, C99
5116 // does not require this promotion.
5117 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5118 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5119 return rhs;
5120 } else { // handle "_Complex double, double".
5121 return lhs;
5122 }
5123 }
5124 return lhs; // The domain/size match exactly.
5125 }
5126 // Now handle "real" floating types (i.e. float, double, long double).
5127 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5128 // if we have an integer operand, the result is the real floating type.
5129 if (rhs->isIntegerType()) {
5130 // convert rhs to the lhs floating point type.
5131 return lhs;
5132 }
5133 if (rhs->isComplexIntegerType()) {
5134 // convert rhs to the complex floating point type.
5135 return getComplexType(lhs);
5136 }
5137 if (lhs->isIntegerType()) {
5138 // convert lhs to the rhs floating point type.
5139 return rhs;
5140 }
Mike Stump11289f42009-09-09 15:08:12 +00005141 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005142 // convert lhs to the complex floating point type.
5143 return getComplexType(rhs);
5144 }
5145 // We have two real floating types, float/complex combos were handled above.
5146 // Convert the smaller operand to the bigger result.
5147 int result = getFloatingTypeOrder(lhs, rhs);
5148 if (result > 0) // convert the rhs
5149 return lhs;
5150 assert(result < 0 && "illegal float comparison");
5151 return rhs; // convert the lhs
5152 }
5153 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5154 // Handle GCC complex int extension.
5155 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5156 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5157
5158 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005159 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005160 rhsComplexInt->getElementType()) >= 0)
5161 return lhs; // convert the rhs
5162 return rhs;
5163 } else if (lhsComplexInt && rhs->isIntegerType()) {
5164 // convert the rhs to the lhs complex type.
5165 return lhs;
5166 } else if (rhsComplexInt && lhs->isIntegerType()) {
5167 // convert the lhs to the rhs complex type.
5168 return rhs;
5169 }
5170 }
5171 // Finally, we have two differing integer types.
5172 // The rules for this case are in C99 6.3.1.8
5173 int compare = getIntegerTypeOrder(lhs, rhs);
5174 bool lhsSigned = lhs->isSignedIntegerType(),
5175 rhsSigned = rhs->isSignedIntegerType();
5176 QualType destType;
5177 if (lhsSigned == rhsSigned) {
5178 // Same signedness; use the higher-ranked type
5179 destType = compare >= 0 ? lhs : rhs;
5180 } else if (compare != (lhsSigned ? 1 : -1)) {
5181 // The unsigned type has greater than or equal rank to the
5182 // signed type, so use the unsigned type
5183 destType = lhsSigned ? rhs : lhs;
5184 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5185 // The two types are different widths; if we are here, that
5186 // means the signed type is larger than the unsigned type, so
5187 // use the signed type.
5188 destType = lhsSigned ? lhs : rhs;
5189 } else {
5190 // The signed type is higher-ranked than the unsigned type,
5191 // but isn't actually any bigger (like unsigned int and long
5192 // on most 32-bit systems). Use the unsigned type corresponding
5193 // to the signed type.
5194 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5195 }
5196 return destType;
5197}