blob: 8230cde3b2d5ba7458ea92e5b1065d18339cd53f [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
Douglas Gregore0fbb832010-03-16 00:06:06 +0000426isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
427 bool Member = false) {
428 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000429 const char *BufferStart
Douglas Gregor802b7762010-03-15 22:54:52 +0000430 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin()),
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000431 &Invalid).data();
Douglas Gregore0fbb832010-03-16 00:06:06 +0000432 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +0000433 return false;
434
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000435 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
436 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000437
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000438 if (End - Start < 4)
439 return false;
440
441 assert(Start[0] == '/' && "Not a comment?");
442 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
443 return false;
444 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
445 return false;
446
447 return (Start[3] == '<') == Member;
448}
449
450/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump11289f42009-09-09 15:08:12 +0000451/// it has one.
Douglas Gregore0fbb832010-03-16 00:06:06 +0000452const char *ASTContext::getCommentForDecl(const Decl *D) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000453 if (!D)
454 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000455
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000456 // Check whether we have cached a comment string for this declaration
457 // already.
Mike Stump11289f42009-09-09 15:08:12 +0000458 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000459 = DeclComments.find(D);
460 if (Pos != DeclComments.end())
461 return Pos->second.c_str();
462
Mike Stump11289f42009-09-09 15:08:12 +0000463 // If we have an external AST source and have not yet loaded comments from
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000464 // that source, do so now.
465 if (ExternalSource && !LoadedExternalComments) {
466 std::vector<SourceRange> LoadedComments;
467 ExternalSource->ReadComments(LoadedComments);
Mike Stump11289f42009-09-09 15:08:12 +0000468
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000469 if (!LoadedComments.empty())
470 Comments.insert(Comments.begin(), LoadedComments.begin(),
471 LoadedComments.end());
Mike Stump11289f42009-09-09 15:08:12 +0000472
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000473 LoadedExternalComments = true;
474 }
Mike Stump11289f42009-09-09 15:08:12 +0000475
476 // If there are no comments anywhere, we won't find anything.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000477 if (Comments.empty())
478 return 0;
479
480 // If the declaration doesn't map directly to a location in a file, we
481 // can't find the comment.
482 SourceLocation DeclStartLoc = D->getLocStart();
483 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
484 return 0;
485
486 // Find the comment that occurs just before this declaration.
487 std::vector<SourceRange>::iterator LastComment
Mike Stump11289f42009-09-09 15:08:12 +0000488 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000489 SourceRange(DeclStartLoc),
490 BeforeInTranslationUnit(&SourceMgr));
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000492 // Decompose the location for the start of the declaration and find the
493 // beginning of the file buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000494 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000495 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000496 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000497 const char *FileBufferStart
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000498 = SourceMgr.getBufferData(DeclStartDecomp.first, &Invalid).data();
Douglas Gregore0fbb832010-03-16 00:06:06 +0000499 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +0000500 return 0;
501
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000502 // First check whether we have a comment for a member.
503 if (LastComment != Comments.end() &&
504 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
Douglas Gregore0fbb832010-03-16 00:06:06 +0000505 isDoxygenComment(SourceMgr, *LastComment, true)) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000506 std::pair<FileID, unsigned> LastCommentEndDecomp
507 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
508 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
509 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump11289f42009-09-09 15:08:12 +0000510 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000511 LastCommentEndDecomp.second)) {
512 // The Doxygen member comment comes after the declaration starts and
513 // is on the same line and in the same file as the declaration. This
514 // is the comment we want.
515 std::string &Result = DeclComments[D];
Mike Stump11289f42009-09-09 15:08:12 +0000516 Result.append(FileBufferStart +
517 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000518 FileBufferStart + LastCommentEndDecomp.second + 1);
519 return Result.c_str();
520 }
521 }
Mike Stump11289f42009-09-09 15:08:12 +0000522
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000523 if (LastComment == Comments.begin())
524 return 0;
525 --LastComment;
526
527 // Decompose the end of the comment.
528 std::pair<FileID, unsigned> LastCommentEndDecomp
529 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000530
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000531 // If the comment and the declaration aren't in the same file, then they
532 // aren't related.
533 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
534 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000536 // Check that we actually have a Doxygen comment.
Douglas Gregore0fbb832010-03-16 00:06:06 +0000537 if (!isDoxygenComment(SourceMgr, *LastComment))
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000538 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000540 // Compute the starting line for the declaration and for the end of the
541 // comment (this is expensive).
Mike Stump11289f42009-09-09 15:08:12 +0000542 unsigned DeclStartLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000543 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
544 unsigned CommentEndLine
Mike Stump11289f42009-09-09 15:08:12 +0000545 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000546 LastCommentEndDecomp.second);
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000548 // If the comment does not end on the line prior to the declaration, then
549 // the comment is not associated with the declaration at all.
550 if (CommentEndLine + 1 != DeclStartLine)
551 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000553 // We have a comment, but there may be more comments on the previous lines.
554 // Keep looking so long as the comments are still Doxygen comments and are
555 // still adjacent.
Mike Stump11289f42009-09-09 15:08:12 +0000556 unsigned ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000557 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
558 std::vector<SourceRange>::iterator FirstComment = LastComment;
559 while (FirstComment != Comments.begin()) {
560 // Look at the previous comment
561 --FirstComment;
562 std::pair<FileID, unsigned> Decomp
563 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000564
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000565 // If this previous comment is in a different file, we're done.
566 if (Decomp.first != DeclStartDecomp.first) {
567 ++FirstComment;
568 break;
569 }
Mike Stump11289f42009-09-09 15:08:12 +0000570
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000571 // If this comment is not a Doxygen comment, we're done.
Douglas Gregore0fbb832010-03-16 00:06:06 +0000572 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000573 ++FirstComment;
574 break;
575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000577 // If the line number is not what we expected, we're done.
578 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
579 if (Line != ExpectedLine) {
580 ++FirstComment;
581 break;
582 }
Mike Stump11289f42009-09-09 15:08:12 +0000583
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000584 // Set the next expected line number.
Mike Stump11289f42009-09-09 15:08:12 +0000585 ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000586 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
587 }
Mike Stump11289f42009-09-09 15:08:12 +0000588
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000589 // The iterator range [FirstComment, LastComment] contains all of the
590 // BCPL comments that, together, are associated with this declaration.
591 // Form a single comment block string for this declaration that concatenates
592 // all of these comments.
593 std::string &Result = DeclComments[D];
594 while (FirstComment != LastComment) {
595 std::pair<FileID, unsigned> DecompStart
596 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
597 std::pair<FileID, unsigned> DecompEnd
598 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
599 Result.append(FileBufferStart + DecompStart.second,
600 FileBufferStart + DecompEnd.second + 1);
601 ++FirstComment;
602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000604 // Append the last comment line.
Mike Stump11289f42009-09-09 15:08:12 +0000605 Result.append(FileBufferStart +
606 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000607 FileBufferStart + LastCommentEndDecomp.second + 1);
608 return Result.c_str();
609}
610
Chris Lattner53cfe802007-07-18 17:52:12 +0000611//===----------------------------------------------------------------------===//
612// Type Sizing and Analysis
613//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000614
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000615/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
616/// scalar floating point type.
617const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000618 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000619 assert(BT && "Not a floating point type!");
620 switch (BT->getKind()) {
621 default: assert(0 && "Not a floating point type!");
622 case BuiltinType::Float: return Target.getFloatFormat();
623 case BuiltinType::Double: return Target.getDoubleFormat();
624 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
625 }
626}
627
Ken Dyck160146e2010-01-27 17:10:57 +0000628/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000629/// specified decl. Note that bitfields do not have a valid alignment, so
630/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000631/// If @p RefAsPointee, references are treated like their underlying type
632/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000633CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000634 unsigned Align = Target.getCharWidth();
635
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000636 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000637 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000638
Chris Lattner68061312009-01-24 21:53:27 +0000639 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
640 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000641 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000642 if (RefAsPointee)
643 T = RT->getPointeeType();
644 else
645 T = getPointerType(RT->getPointeeType());
646 }
647 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000648 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000649 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
650 T = cast<ArrayType>(T)->getElementType();
651
652 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
653 }
Charles Davis3fc51072010-02-23 04:52:00 +0000654 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
655 // In the case of a field in a packed struct, we want the minimum
656 // of the alignment of the field and the alignment of the struct.
657 Align = std::min(Align,
658 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
659 }
Chris Lattner68061312009-01-24 21:53:27 +0000660 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000661
Ken Dyck160146e2010-01-27 17:10:57 +0000662 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000663}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000664
Chris Lattner983a8bb2007-07-13 22:13:22 +0000665/// getTypeSize - Return the size of the specified type, in bits. This method
666/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000667///
668/// FIXME: Pointers into different addr spaces could have different sizes and
669/// alignment requirements: getPointerInfo should take an AddrSpace, this
670/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000671std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000672ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000673 uint64_t Width=0;
674 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000675 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000676#define TYPE(Class, Base)
677#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000678#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000679#define DEPENDENT_TYPE(Class, Base) case Type::Class:
680#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000681 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000682 break;
683
Chris Lattner355332d2007-07-13 22:27:08 +0000684 case Type::FunctionNoProto:
685 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000686 // GCC extension: alignof(function) = 32 bits
687 Width = 0;
688 Align = 32;
689 break;
690
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000691 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000692 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000693 Width = 0;
694 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
695 break;
696
Steve Naroff5c131802007-08-30 01:06:46 +0000697 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000698 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner37e05872008-03-05 18:54:05 +0000700 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000701 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000702 Align = EltInfo.second;
703 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000704 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000705 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000706 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000707 const VectorType *VT = cast<VectorType>(T);
708 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
709 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000710 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000711 // If the alignment is not a power of 2, round up to the next power of 2.
712 // This happens for non-power-of-2 length vectors.
Chris Lattner63d2b362009-10-22 05:17:15 +0000713 if (VT->getNumElements() & (VT->getNumElements()-1)) {
714 Align = llvm::NextPowerOf2(Align);
715 Width = llvm::RoundUpToAlignment(Width, Align);
716 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000717 break;
718 }
Chris Lattner647fb222007-07-18 18:26:58 +0000719
Chris Lattner7570e9c2008-03-08 08:52:55 +0000720 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000721 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000722 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000723 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000724 // GCC extension: alignof(void) = 8 bits.
725 Width = 0;
726 Align = 8;
727 break;
728
Chris Lattner6a4f7452007-12-19 19:23:28 +0000729 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000730 Width = Target.getBoolWidth();
731 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000732 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000733 case BuiltinType::Char_S:
734 case BuiltinType::Char_U:
735 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000736 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000737 Width = Target.getCharWidth();
738 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000739 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000740 case BuiltinType::WChar:
741 Width = Target.getWCharWidth();
742 Align = Target.getWCharAlign();
743 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000744 case BuiltinType::Char16:
745 Width = Target.getChar16Width();
746 Align = Target.getChar16Align();
747 break;
748 case BuiltinType::Char32:
749 Width = Target.getChar32Width();
750 Align = Target.getChar32Align();
751 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000752 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000753 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000754 Width = Target.getShortWidth();
755 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000756 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000757 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000758 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000759 Width = Target.getIntWidth();
760 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000761 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000762 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000763 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000764 Width = Target.getLongWidth();
765 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000766 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000767 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000768 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000769 Width = Target.getLongLongWidth();
770 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000771 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000772 case BuiltinType::Int128:
773 case BuiltinType::UInt128:
774 Width = 128;
775 Align = 128; // int128_t is 128-bit aligned on all targets.
776 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000777 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000778 Width = Target.getFloatWidth();
779 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 break;
781 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000782 Width = Target.getDoubleWidth();
783 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000784 break;
785 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000786 Width = Target.getLongDoubleWidth();
787 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000788 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000789 case BuiltinType::NullPtr:
790 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
791 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000792 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000793 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000794 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000795 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000796 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000797 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000798 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000799 case Type::BlockPointer: {
800 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
801 Width = Target.getPointerWidth(AS);
802 Align = Target.getPointerAlign(AS);
803 break;
804 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000805 case Type::LValueReference:
806 case Type::RValueReference: {
807 // alignof and sizeof should never enter this code path here, so we go
808 // the pointer route.
809 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
810 Width = Target.getPointerWidth(AS);
811 Align = Target.getPointerAlign(AS);
812 break;
813 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000814 case Type::Pointer: {
815 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000816 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000817 Align = Target.getPointerAlign(AS);
818 break;
819 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000820 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000821 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000822 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000823 getTypeInfo(getPointerDiffType());
824 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000825 if (Pointee->isFunctionType())
826 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000827 Align = PtrDiffInfo.second;
828 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000829 }
Chris Lattner647fb222007-07-18 18:26:58 +0000830 case Type::Complex: {
831 // Complex types have the same alignment as their elements, but twice the
832 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000833 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000834 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000835 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000836 Align = EltInfo.second;
837 break;
838 }
Devang Pateldbb72632008-06-04 21:54:36 +0000839 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000840 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000841 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
842 Width = Layout.getSize();
843 Align = Layout.getAlignment();
844 break;
845 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000846 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000847 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000848 const TagType *TT = cast<TagType>(T);
849
850 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000851 Width = 1;
852 Align = 1;
853 break;
854 }
Mike Stump11289f42009-09-09 15:08:12 +0000855
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000856 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000857 return getTypeInfo(ET->getDecl()->getIntegerType());
858
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000859 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000860 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
861 Width = Layout.getSize();
862 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000863 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000864 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000865
Chris Lattner63d2b362009-10-22 05:17:15 +0000866 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000867 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
868 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000869
Chris Lattner63d2b362009-10-22 05:17:15 +0000870 case Type::Elaborated:
871 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
872 .getTypePtr());
John McCallfcc33b02009-09-05 00:15:47 +0000873
Douglas Gregoref462e62009-04-30 17:32:17 +0000874 case Type::Typedef: {
875 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000876 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000877 Align = std::max(Aligned->getMaxAlignment(),
878 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000879 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
880 } else
881 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000882 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000883 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000884
885 case Type::TypeOfExpr:
886 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
887 .getTypePtr());
888
889 case Type::TypeOf:
890 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
891
Anders Carlsson81df7b82009-06-24 19:06:50 +0000892 case Type::Decltype:
893 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
894 .getTypePtr());
895
Douglas Gregoref462e62009-04-30 17:32:17 +0000896 case Type::QualifiedName:
897 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000898
John McCalle78aac42010-03-10 03:28:59 +0000899 case Type::InjectedClassName:
900 return getTypeInfo(cast<InjectedClassNameType>(T)
901 ->getUnderlyingType().getTypePtr());
902
Douglas Gregoref462e62009-04-30 17:32:17 +0000903 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000904 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000905 "Cannot request the size of a dependent type");
906 // FIXME: this is likely to be wrong once we support template
907 // aliases, since a template alias could refer to a typedef that
908 // has an __aligned__ attribute on it.
909 return getTypeInfo(getCanonicalType(T));
910 }
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattner53cfe802007-07-18 17:52:12 +0000912 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000913 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000914}
915
Ken Dyck8c89d592009-12-22 14:23:30 +0000916/// getTypeSizeInChars - Return the size of the specified type, in characters.
917/// This method does not work on incomplete types.
918CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000919 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000920}
921CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000922 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000923}
924
Ken Dycka6046ab2010-01-26 17:25:18 +0000925/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000926/// characters. This method does not work on incomplete types.
927CharUnits ASTContext::getTypeAlignInChars(QualType T) {
928 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
929}
930CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
931 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
932}
933
Chris Lattnera3402cd2009-01-27 18:08:34 +0000934/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
935/// type for the current target in bits. This can be different than the ABI
936/// alignment in cases where it is beneficial for performance to overalign
937/// a data type.
938unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
939 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000940
941 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000942 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000943 T = CT->getElementType().getTypePtr();
944 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
945 T->isSpecificBuiltinType(BuiltinType::LongLong))
946 return std::max(ABIAlign, (unsigned)getTypeSize(T));
947
Chris Lattnera3402cd2009-01-27 18:08:34 +0000948 return ABIAlign;
949}
950
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000951static void CollectLocalObjCIvars(ASTContext *Ctx,
952 const ObjCInterfaceDecl *OI,
953 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000954 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
955 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000956 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000957 if (!IVDecl->isInvalidDecl())
958 Fields.push_back(cast<FieldDecl>(IVDecl));
959 }
960}
961
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000962void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
963 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
964 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
965 CollectObjCIvars(SuperClass, Fields);
966 CollectLocalObjCIvars(this, OI, Fields);
967}
968
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000969/// ShallowCollectObjCIvars -
970/// Collect all ivars, including those synthesized, in the current class.
971///
972void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000973 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000974 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
975 E = OI->ivar_end(); I != E; ++I) {
976 Ivars.push_back(*I);
977 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000978
979 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000980}
981
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000982/// CollectNonClassIvars -
983/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000984/// This includes synthesized ivars (via @synthesize) and those in
985// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000986///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000987void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000988 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000989 // Find ivars declared in class extension.
990 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
991 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
992 E = CDecl->ivar_end(); I != E; ++I) {
993 Ivars.push_back(*I);
994 }
995 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000996
Ted Kremenek86838aa2010-03-11 19:44:54 +0000997 // Also add any ivar defined in this class's implementation. This
998 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000999 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1000 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1001 E = ImplDecl->ivar_end(); I != E; ++I)
1002 Ivars.push_back(*I);
1003 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001004}
1005
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001006/// CollectInheritedProtocols - Collect all protocols in current class and
1007/// those inherited by it.
1008void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001009 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001010 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1011 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1012 PE = OI->protocol_end(); P != PE; ++P) {
1013 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001014 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001015 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001016 PE = Proto->protocol_end(); P != PE; ++P) {
1017 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001018 CollectInheritedProtocols(*P, Protocols);
1019 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001020 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001021
1022 // Categories of this Interface.
1023 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1024 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1025 CollectInheritedProtocols(CDeclChain, Protocols);
1026 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1027 while (SD) {
1028 CollectInheritedProtocols(SD, Protocols);
1029 SD = SD->getSuperClass();
1030 }
1031 return;
1032 }
1033 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1034 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1035 PE = OC->protocol_end(); P != PE; ++P) {
1036 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001037 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001038 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1039 PE = Proto->protocol_end(); P != PE; ++P)
1040 CollectInheritedProtocols(*P, Protocols);
1041 }
1042 return;
1043 }
1044 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1045 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1046 PE = OP->protocol_end(); P != PE; ++P) {
1047 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001048 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001049 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1050 PE = Proto->protocol_end(); P != PE; ++P)
1051 CollectInheritedProtocols(*P, Protocols);
1052 }
1053 return;
1054 }
1055}
1056
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001057unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1058 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001059 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1060 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001061 if ((*I)->getPropertyIvarDecl())
1062 ++count;
1063
1064 // Also look into nested protocols.
1065 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1066 E = PD->protocol_end(); P != E; ++P)
1067 count += CountProtocolSynthesizedIvars(*P);
1068 return count;
1069}
1070
Mike Stump11289f42009-09-09 15:08:12 +00001071unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001072 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001073 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1074 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001075 if ((*I)->getPropertyIvarDecl())
1076 ++count;
1077 }
1078 // Also look into interface's protocol list for properties declared
1079 // in the protocol and whose ivars are synthesized.
1080 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1081 PE = OI->protocol_end(); P != PE; ++P) {
1082 ObjCProtocolDecl *PD = (*P);
1083 count += CountProtocolSynthesizedIvars(PD);
1084 }
1085 return count;
1086}
1087
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001088/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1089ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1090 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1091 I = ObjCImpls.find(D);
1092 if (I != ObjCImpls.end())
1093 return cast<ObjCImplementationDecl>(I->second);
1094 return 0;
1095}
1096/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1097ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1098 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1099 I = ObjCImpls.find(D);
1100 if (I != ObjCImpls.end())
1101 return cast<ObjCCategoryImplDecl>(I->second);
1102 return 0;
1103}
1104
1105/// \brief Set the implementation of ObjCInterfaceDecl.
1106void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1107 ObjCImplementationDecl *ImplD) {
1108 assert(IFaceD && ImplD && "Passed null params");
1109 ObjCImpls[IFaceD] = ImplD;
1110}
1111/// \brief Set the implementation of ObjCCategoryDecl.
1112void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1113 ObjCCategoryImplDecl *ImplD) {
1114 assert(CatD && ImplD && "Passed null params");
1115 ObjCImpls[CatD] = ImplD;
1116}
1117
John McCallbcd03502009-12-07 02:54:59 +00001118/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001119///
John McCallbcd03502009-12-07 02:54:59 +00001120/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001121/// the TypeLoc wrappers.
1122///
1123/// \param T the type that will be the basis for type source info. This type
1124/// should refer to how the declarator was written in source code, not to
1125/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001126TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001127 unsigned DataSize) {
1128 if (!DataSize)
1129 DataSize = TypeLoc::getFullDataSizeForType(T);
1130 else
1131 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001132 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001133
John McCallbcd03502009-12-07 02:54:59 +00001134 TypeSourceInfo *TInfo =
1135 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1136 new (TInfo) TypeSourceInfo(T);
1137 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001138}
1139
John McCallbcd03502009-12-07 02:54:59 +00001140TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001141 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001142 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001143 DI->getTypeLoc().initialize(L);
1144 return DI;
1145}
1146
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001147/// getInterfaceLayoutImpl - Get or compute information about the
1148/// layout of the given interface.
1149///
1150/// \param Impl - If given, also include the layout of the interface's
1151/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +00001152const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001153ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1154 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +00001155 assert(!D->isForwardDecl() && "Invalid interface decl!");
1156
Devang Pateldbb72632008-06-04 21:54:36 +00001157 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +00001158 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001159 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1160 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1161 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +00001162
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001163 // Add in synthesized ivar count if laying out an implementation.
1164 if (Impl) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001165 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001166 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001167 // entry. Note we can't cache this because we simply free all
1168 // entries later; however we shouldn't look up implementations
1169 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001170 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001171 return getObjCLayout(D, 0);
1172 }
1173
Mike Stump11289f42009-09-09 15:08:12 +00001174 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001175 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1176 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001177
Devang Pateldbb72632008-06-04 21:54:36 +00001178 return *NewEntry;
1179}
1180
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001181const ASTRecordLayout &
1182ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1183 return getObjCLayout(D, 0);
1184}
1185
1186const ASTRecordLayout &
1187ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1188 return getObjCLayout(D->getClassInterface(), D);
1189}
1190
Devang Patele11664a2007-11-01 19:11:01 +00001191/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +00001192/// specified record (struct/union/class), which indicates its size and field
1193/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +00001194const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001195 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +00001196 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +00001197
Chris Lattner53cfe802007-07-18 17:52:12 +00001198 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +00001199 // Note that we can't save a reference to the entry because this function
1200 // is recursive.
1201 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +00001202 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +00001203
Mike Stump11289f42009-09-09 15:08:12 +00001204 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001205 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +00001206 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001207
Chris Lattner647fb222007-07-18 18:26:58 +00001208 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +00001209}
1210
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001211const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001212 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001213 assert(RD && "Cannot get key function for forward declarations!");
1214
1215 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1216 if (!Entry)
1217 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1218 else
1219 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1220 "Key function changed!");
1221
1222 return Entry;
1223}
1224
Chris Lattner983a8bb2007-07-13 22:13:22 +00001225//===----------------------------------------------------------------------===//
1226// Type creation/memoization methods
1227//===----------------------------------------------------------------------===//
1228
John McCall8ccfcb52009-09-24 19:53:00 +00001229QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1230 unsigned Fast = Quals.getFastQualifiers();
1231 Quals.removeFastQualifiers();
1232
1233 // Check if we've already instantiated this type.
1234 llvm::FoldingSetNodeID ID;
1235 ExtQuals::Profile(ID, TypeNode, Quals);
1236 void *InsertPos = 0;
1237 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1238 assert(EQ->getQualifiers() == Quals);
1239 QualType T = QualType(EQ, Fast);
1240 return T;
1241 }
1242
John McCall90d1c2d2009-09-24 23:30:46 +00001243 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001244 ExtQualNodes.InsertNode(New, InsertPos);
1245 QualType T = QualType(New, Fast);
1246 return T;
1247}
1248
1249QualType ASTContext::getVolatileType(QualType T) {
1250 QualType CanT = getCanonicalType(T);
1251 if (CanT.isVolatileQualified()) return T;
1252
1253 QualifierCollector Quals;
1254 const Type *TypeNode = Quals.strip(T);
1255 Quals.addVolatile();
1256
1257 return getExtQualType(TypeNode, Quals);
1258}
1259
Fariborz Jahanianece85822009-02-17 18:27:45 +00001260QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001261 QualType CanT = getCanonicalType(T);
1262 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001263 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001264
John McCall8ccfcb52009-09-24 19:53:00 +00001265 // If we are composing extended qualifiers together, merge together
1266 // into one ExtQuals node.
1267 QualifierCollector Quals;
1268 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001269
John McCall8ccfcb52009-09-24 19:53:00 +00001270 // If this type already has an address space specified, it cannot get
1271 // another one.
1272 assert(!Quals.hasAddressSpace() &&
1273 "Type cannot be in multiple addr spaces!");
1274 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001275
John McCall8ccfcb52009-09-24 19:53:00 +00001276 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001277}
1278
Chris Lattnerd60183d2009-02-18 22:53:11 +00001279QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001280 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001281 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001282 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001283 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001284
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001285 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001287 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001288 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1289 return getPointerType(ResultType);
1290 }
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCall8ccfcb52009-09-24 19:53:00 +00001293 // If we are composing extended qualifiers together, merge together
1294 // into one ExtQuals node.
1295 QualifierCollector Quals;
1296 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001297
John McCall8ccfcb52009-09-24 19:53:00 +00001298 // If this type already has an ObjCGC specified, it cannot get
1299 // another one.
1300 assert(!Quals.hasObjCGCAttr() &&
1301 "Type cannot have multiple ObjCGCs!");
1302 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001303
John McCall8ccfcb52009-09-24 19:53:00 +00001304 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001305}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001306
Douglas Gregor8c940862010-01-18 17:14:39 +00001307static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1308 bool AddNoReturn,
1309 CallingConv CallConv) {
John McCall8ccfcb52009-09-24 19:53:00 +00001310 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001311 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1312 QualType Pointee = Pointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001313 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1314 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001315 if (ResultType == Pointee)
1316 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001317
1318 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001319 } else if (const BlockPointerType *BlockPointer
1320 = T->getAs<BlockPointerType>()) {
1321 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001322 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1323 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001324 if (ResultType == Pointee)
1325 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001326
1327 ResultType = Context.getBlockPointerType(ResultType);
1328 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1329 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001330 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001331
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001332 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001333 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1334 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001335 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001336 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001337 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001338 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1339 FPT->getNumArgs(), FPT->isVariadic(),
1340 FPT->getTypeQuals(),
1341 FPT->hasExceptionSpec(),
1342 FPT->hasAnyExceptionSpec(),
1343 FPT->getNumExceptions(),
1344 FPT->exception_begin(),
1345 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001346 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001347 } else
1348 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001349
1350 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1351}
1352
1353QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1354 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1355}
1356
1357QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1358 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump8c5d7992009-07-25 21:26:53 +00001359}
1360
Chris Lattnerc6395932007-06-22 20:56:16 +00001361/// getComplexType - Return the uniqued reference to the type for a complex
1362/// number with the specified element type.
1363QualType ASTContext::getComplexType(QualType T) {
1364 // Unique pointers, to guarantee there is only one pointer of a particular
1365 // structure.
1366 llvm::FoldingSetNodeID ID;
1367 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerc6395932007-06-22 20:56:16 +00001369 void *InsertPos = 0;
1370 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1371 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattnerc6395932007-06-22 20:56:16 +00001373 // If the pointee type isn't canonical, this won't be a canonical type either,
1374 // so fill in the canonical type field.
1375 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001376 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001377 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattnerc6395932007-06-22 20:56:16 +00001379 // Get the new insert position for the node we care about.
1380 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001381 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001382 }
John McCall90d1c2d2009-09-24 23:30:46 +00001383 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001384 Types.push_back(New);
1385 ComplexTypes.InsertNode(New, InsertPos);
1386 return QualType(New, 0);
1387}
1388
Chris Lattner970e54e2006-11-12 00:37:36 +00001389/// getPointerType - Return the uniqued reference to the type for a pointer to
1390/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001392 // Unique pointers, to guarantee there is only one pointer of a particular
1393 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001394 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001395 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001396
Chris Lattner67521df2007-01-27 01:29:36 +00001397 void *InsertPos = 0;
1398 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001399 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001400
Chris Lattner7ccecb92006-11-12 08:50:50 +00001401 // If the pointee type isn't canonical, this won't be a canonical type either,
1402 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001403 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001404 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001405 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattner67521df2007-01-27 01:29:36 +00001407 // Get the new insert position for the node we care about.
1408 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001409 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001410 }
John McCall90d1c2d2009-09-24 23:30:46 +00001411 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001412 Types.push_back(New);
1413 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001414 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001415}
1416
Mike Stump11289f42009-09-09 15:08:12 +00001417/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001418/// a pointer to the specified block.
1419QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001420 assert(T->isFunctionType() && "block of function types only");
1421 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001422 // structure.
1423 llvm::FoldingSetNodeID ID;
1424 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Steve Naroffec33ed92008-08-27 16:04:49 +00001426 void *InsertPos = 0;
1427 if (BlockPointerType *PT =
1428 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1429 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001430
1431 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001432 // type either so fill in the canonical type field.
1433 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001434 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001435 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001436
Steve Naroffec33ed92008-08-27 16:04:49 +00001437 // Get the new insert position for the node we care about.
1438 BlockPointerType *NewIP =
1439 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001440 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001441 }
John McCall90d1c2d2009-09-24 23:30:46 +00001442 BlockPointerType *New
1443 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001444 Types.push_back(New);
1445 BlockPointerTypes.InsertNode(New, InsertPos);
1446 return QualType(New, 0);
1447}
1448
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001449/// getLValueReferenceType - Return the uniqued reference to the type for an
1450/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001451QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001452 // Unique pointers, to guarantee there is only one pointer of a particular
1453 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001454 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001455 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001456
1457 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001458 if (LValueReferenceType *RT =
1459 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001460 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001461
John McCallfc93cf92009-10-22 22:37:11 +00001462 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1463
Bill Wendling3708c182007-05-27 10:15:43 +00001464 // If the referencee type isn't canonical, this won't be a canonical type
1465 // either, so fill in the canonical type field.
1466 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001467 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1468 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1469 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001470
Bill Wendling3708c182007-05-27 10:15:43 +00001471 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001472 LValueReferenceType *NewIP =
1473 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001474 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001475 }
1476
John McCall90d1c2d2009-09-24 23:30:46 +00001477 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001478 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1479 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001480 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001481 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001482
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001483 return QualType(New, 0);
1484}
1485
1486/// getRValueReferenceType - Return the uniqued reference to the type for an
1487/// rvalue reference to the specified type.
1488QualType ASTContext::getRValueReferenceType(QualType T) {
1489 // Unique pointers, to guarantee there is only one pointer of a particular
1490 // structure.
1491 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001492 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001493
1494 void *InsertPos = 0;
1495 if (RValueReferenceType *RT =
1496 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1497 return QualType(RT, 0);
1498
John McCallfc93cf92009-10-22 22:37:11 +00001499 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1500
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001501 // If the referencee type isn't canonical, this won't be a canonical type
1502 // either, so fill in the canonical type field.
1503 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001504 if (InnerRef || !T.isCanonical()) {
1505 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1506 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001507
1508 // Get the new insert position for the node we care about.
1509 RValueReferenceType *NewIP =
1510 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1511 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1512 }
1513
John McCall90d1c2d2009-09-24 23:30:46 +00001514 RValueReferenceType *New
1515 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001516 Types.push_back(New);
1517 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001518 return QualType(New, 0);
1519}
1520
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001521/// getMemberPointerType - Return the uniqued reference to the type for a
1522/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001523QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001524 // Unique pointers, to guarantee there is only one pointer of a particular
1525 // structure.
1526 llvm::FoldingSetNodeID ID;
1527 MemberPointerType::Profile(ID, T, Cls);
1528
1529 void *InsertPos = 0;
1530 if (MemberPointerType *PT =
1531 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1532 return QualType(PT, 0);
1533
1534 // If the pointee or class type isn't canonical, this won't be a canonical
1535 // type either, so fill in the canonical type field.
1536 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001537 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001538 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1539
1540 // Get the new insert position for the node we care about.
1541 MemberPointerType *NewIP =
1542 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1543 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1544 }
John McCall90d1c2d2009-09-24 23:30:46 +00001545 MemberPointerType *New
1546 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001547 Types.push_back(New);
1548 MemberPointerTypes.InsertNode(New, InsertPos);
1549 return QualType(New, 0);
1550}
1551
Mike Stump11289f42009-09-09 15:08:12 +00001552/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001553/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001554QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001555 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001556 ArrayType::ArraySizeModifier ASM,
1557 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001558 assert((EltTy->isDependentType() ||
1559 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001560 "Constant array of VLAs is illegal!");
1561
Chris Lattnere2df3f92009-05-13 04:12:56 +00001562 // Convert the array size into a canonical width matching the pointer size for
1563 // the target.
1564 llvm::APInt ArySize(ArySizeIn);
1565 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattner23b7eb62007-06-15 23:05:46 +00001567 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001568 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001569
Chris Lattner36f8e652007-01-27 08:31:04 +00001570 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001571 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001572 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001573 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattner7ccecb92006-11-12 08:50:50 +00001575 // If the element type isn't canonical, this won't be a canonical type either,
1576 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001577 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001578 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001579 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001580 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001581 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001582 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001583 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001584 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall90d1c2d2009-09-24 23:30:46 +00001587 ConstantArrayType *New = new(*this,TypeAlignment)
1588 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001589 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001590 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001591 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001592}
1593
Steve Naroffcadebd02007-08-30 18:14:25 +00001594/// getVariableArrayType - Returns a non-unique reference to the type for a
1595/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001596QualType ASTContext::getVariableArrayType(QualType EltTy,
1597 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001598 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001599 unsigned EltTypeQuals,
1600 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001601 // Since we don't unique expressions, it isn't possible to unique VLA's
1602 // that have an expression provided for their size.
1603
John McCall90d1c2d2009-09-24 23:30:46 +00001604 VariableArrayType *New = new(*this, TypeAlignment)
1605 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001606
1607 VariableArrayTypes.push_back(New);
1608 Types.push_back(New);
1609 return QualType(New, 0);
1610}
1611
Douglas Gregor4619e432008-12-05 23:32:09 +00001612/// getDependentSizedArrayType - Returns a non-unique reference to
1613/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001614/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001615QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1616 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001617 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001618 unsigned EltTypeQuals,
1619 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001620 assert((!NumElts || NumElts->isTypeDependent() ||
1621 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001622 "Size must be type- or value-dependent!");
1623
Douglas Gregorf3f95522009-07-31 00:23:35 +00001624 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001625 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001626 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001627
1628 if (NumElts) {
1629 // Dependently-sized array types that do not have a specified
1630 // number of elements will have their sizes deduced from an
1631 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001632 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1633 EltTypeQuals, NumElts);
1634
1635 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1636 }
1637
Douglas Gregorf3f95522009-07-31 00:23:35 +00001638 DependentSizedArrayType *New;
1639 if (Canon) {
1640 // We already have a canonical version of this array type; use it as
1641 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001642 New = new (*this, TypeAlignment)
1643 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1644 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001645 } else {
1646 QualType CanonEltTy = getCanonicalType(EltTy);
1647 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001648 New = new (*this, TypeAlignment)
1649 DependentSizedArrayType(*this, EltTy, QualType(),
1650 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001651
Douglas Gregorc42075a2010-02-04 18:10:26 +00001652 if (NumElts) {
1653 DependentSizedArrayType *CanonCheck
1654 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1655 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1656 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001657 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001658 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001659 } else {
1660 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1661 ASM, EltTypeQuals,
1662 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001663 New = new (*this, TypeAlignment)
1664 DependentSizedArrayType(*this, EltTy, Canon,
1665 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001666 }
1667 }
Mike Stump11289f42009-09-09 15:08:12 +00001668
Douglas Gregor4619e432008-12-05 23:32:09 +00001669 Types.push_back(New);
1670 return QualType(New, 0);
1671}
1672
Eli Friedmanbd258282008-02-15 18:16:39 +00001673QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1674 ArrayType::ArraySizeModifier ASM,
1675 unsigned EltTypeQuals) {
1676 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001677 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001678
1679 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001680 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001681 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1682 return QualType(ATP, 0);
1683
1684 // If the element type isn't canonical, this won't be a canonical type
1685 // either, so fill in the canonical type field.
1686 QualType Canonical;
1687
John McCallb692a092009-10-22 20:10:53 +00001688 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001689 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001690 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001691
1692 // Get the new insert position for the node we care about.
1693 IncompleteArrayType *NewIP =
1694 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001695 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001696 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001697
John McCall90d1c2d2009-09-24 23:30:46 +00001698 IncompleteArrayType *New = new (*this, TypeAlignment)
1699 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001700
1701 IncompleteArrayTypes.InsertNode(New, InsertPos);
1702 Types.push_back(New);
1703 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001704}
1705
Steve Naroff91fcddb2007-07-18 18:00:27 +00001706/// getVectorType - Return the unique reference to a vector type of
1707/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001708QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1709 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001710 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattner76a00cf2008-04-06 22:59:24 +00001712 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001713 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001714
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001715 // Check if we've already instantiated a vector of this type.
1716 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001717 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1718 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001719 void *InsertPos = 0;
1720 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1721 return QualType(VTP, 0);
1722
1723 // If the element type isn't canonical, this won't be a canonical type either,
1724 // so fill in the canonical type field.
1725 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001726 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1727 Canonical = getVectorType(getCanonicalType(vecType),
1728 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001729
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001730 // Get the new insert position for the node we care about.
1731 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001732 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001733 }
John McCall90d1c2d2009-09-24 23:30:46 +00001734 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001735 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001736 VectorTypes.InsertNode(New, InsertPos);
1737 Types.push_back(New);
1738 return QualType(New, 0);
1739}
1740
Nate Begemance4d7fc2008-04-18 23:10:10 +00001741/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001742/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001743QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001744 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Chris Lattner76a00cf2008-04-06 22:59:24 +00001746 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001747 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001748
Steve Naroff91fcddb2007-07-18 18:00:27 +00001749 // Check if we've already instantiated a vector of this type.
1750 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001751 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001752 void *InsertPos = 0;
1753 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1754 return QualType(VTP, 0);
1755
1756 // If the element type isn't canonical, this won't be a canonical type either,
1757 // so fill in the canonical type field.
1758 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001759 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001760 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001761
Steve Naroff91fcddb2007-07-18 18:00:27 +00001762 // Get the new insert position for the node we care about.
1763 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001764 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001765 }
John McCall90d1c2d2009-09-24 23:30:46 +00001766 ExtVectorType *New = new (*this, TypeAlignment)
1767 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001768 VectorTypes.InsertNode(New, InsertPos);
1769 Types.push_back(New);
1770 return QualType(New, 0);
1771}
1772
Mike Stump11289f42009-09-09 15:08:12 +00001773QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001774 Expr *SizeExpr,
1775 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001776 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001777 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001778 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Douglas Gregor352169a2009-07-31 03:54:25 +00001780 void *InsertPos = 0;
1781 DependentSizedExtVectorType *Canon
1782 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1783 DependentSizedExtVectorType *New;
1784 if (Canon) {
1785 // We already have a canonical version of this array type; use it as
1786 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001787 New = new (*this, TypeAlignment)
1788 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1789 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001790 } else {
1791 QualType CanonVecTy = getCanonicalType(vecType);
1792 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001793 New = new (*this, TypeAlignment)
1794 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1795 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001796
1797 DependentSizedExtVectorType *CanonCheck
1798 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1799 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1800 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001801 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1802 } else {
1803 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1804 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001805 New = new (*this, TypeAlignment)
1806 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001807 }
1808 }
Mike Stump11289f42009-09-09 15:08:12 +00001809
Douglas Gregor758a8692009-06-17 21:51:59 +00001810 Types.push_back(New);
1811 return QualType(New, 0);
1812}
1813
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001814/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001815///
Douglas Gregor8c940862010-01-18 17:14:39 +00001816QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1817 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001818 // Unique functions, to guarantee there is only one function of a particular
1819 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001820 llvm::FoldingSetNodeID ID;
John McCallcddbad02010-02-04 05:44:44 +00001821 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump11289f42009-09-09 15:08:12 +00001822
Chris Lattner47955de2007-01-27 08:37:20 +00001823 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001824 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001825 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001826 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001827
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001828 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001829 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001830 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001831 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001832 getCanonicalCallConv(CallConv));
Mike Stump11289f42009-09-09 15:08:12 +00001833
Chris Lattner47955de2007-01-27 08:37:20 +00001834 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001835 FunctionNoProtoType *NewIP =
1836 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001837 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
John McCall90d1c2d2009-09-24 23:30:46 +00001840 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallcddbad02010-02-04 05:44:44 +00001841 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Chris Lattner47955de2007-01-27 08:37:20 +00001842 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001843 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001844 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001845}
1846
1847/// getFunctionType - Return a normal function type with a typed argument
1848/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001849QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001850 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001851 unsigned TypeQuals, bool hasExceptionSpec,
1852 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregor8c940862010-01-18 17:14:39 +00001853 const QualType *ExArray, bool NoReturn,
1854 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001855 // Unique functions, to guarantee there is only one function of a particular
1856 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001857 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001858 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001859 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallcddbad02010-02-04 05:44:44 +00001860 NumExs, ExArray, NoReturn, CallConv);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001861
1862 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001863 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001864 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001865 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001866
1867 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001868 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001869 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001870 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001871 isCanonical = false;
1872
1873 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001874 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001875 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001876 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001877 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001878 CanonicalArgs.reserve(NumArgs);
1879 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001880 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001881
Chris Lattner76a00cf2008-04-06 22:59:24 +00001882 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001883 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001884 isVariadic, TypeQuals, false,
Douglas Gregor8c940862010-01-18 17:14:39 +00001885 false, 0, 0, NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001886 getCanonicalCallConv(CallConv));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001887
Chris Lattnerfd4de792007-01-27 01:15:32 +00001888 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001889 FunctionProtoType *NewIP =
1890 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001891 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001892 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001893
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001894 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001895 // for two variable size arrays (for parameter and exception types) at the
1896 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001897 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001898 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1899 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001900 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001901 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001902 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregor8c940862010-01-18 17:14:39 +00001903 ExArray, NumExs, Canonical, NoReturn, CallConv);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001904 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001905 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001906 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001907}
Chris Lattneref51c202006-11-10 07:17:23 +00001908
John McCalle78aac42010-03-10 03:28:59 +00001909#ifndef NDEBUG
1910static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1911 if (!isa<CXXRecordDecl>(D)) return false;
1912 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1913 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1914 return true;
1915 if (RD->getDescribedClassTemplate() &&
1916 !isa<ClassTemplateSpecializationDecl>(RD))
1917 return true;
1918 return false;
1919}
1920#endif
1921
1922/// getInjectedClassNameType - Return the unique reference to the
1923/// injected class name type for the specified templated declaration.
1924QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1925 QualType TST) {
1926 assert(NeedsInjectedClassNameType(Decl));
1927 if (Decl->TypeForDecl) {
1928 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1929 } else if (CXXRecordDecl *PrevDecl
1930 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1931 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1932 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1933 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1934 } else {
1935 Decl->TypeForDecl = new (*this, TypeAlignment)
1936 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1937 Types.push_back(Decl->TypeForDecl);
1938 }
1939 return QualType(Decl->TypeForDecl, 0);
1940}
1941
Douglas Gregor83a586e2008-04-13 21:07:44 +00001942/// getTypeDeclType - Return the unique reference to the type for the
1943/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001944QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001945 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001946 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001947
John McCall81e38502010-02-16 03:57:14 +00001948 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001949 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001950
1951 if (const ObjCInterfaceDecl *ObjCInterface
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001952 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001953 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001954
John McCall96f0b5f2010-03-10 06:48:02 +00001955 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1956 "Template type parameter types are always available.");
1957
John McCall81e38502010-02-16 03:57:14 +00001958 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001959 assert(!Record->getPreviousDeclaration() &&
1960 "struct/union has previous declaration");
1961 assert(!NeedsInjectedClassNameType(Record));
1962 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001963 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001964 assert(!Enum->getPreviousDeclaration() &&
1965 "enum has previous declaration");
1966 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001967 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001968 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1969 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001970 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001971 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001972
John McCall96f0b5f2010-03-10 06:48:02 +00001973 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001974 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001975}
1976
Chris Lattner32d920b2007-01-26 02:01:53 +00001977/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001978/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001979QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001980 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattner76a00cf2008-04-06 22:59:24 +00001982 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001983 Decl->TypeForDecl = new(*this, TypeAlignment)
1984 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001985 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001986 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001987}
1988
John McCallcebee162009-10-18 09:09:24 +00001989/// \brief Retrieve a substitution-result type.
1990QualType
1991ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1992 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001993 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001994 && "replacement types must always be canonical");
1995
1996 llvm::FoldingSetNodeID ID;
1997 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1998 void *InsertPos = 0;
1999 SubstTemplateTypeParmType *SubstParm
2000 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2001
2002 if (!SubstParm) {
2003 SubstParm = new (*this, TypeAlignment)
2004 SubstTemplateTypeParmType(Parm, Replacement);
2005 Types.push_back(SubstParm);
2006 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2007 }
2008
2009 return QualType(SubstParm, 0);
2010}
2011
Douglas Gregoreff93e02009-02-05 23:33:38 +00002012/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002013/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002014/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002015QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002016 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00002017 IdentifierInfo *Name) {
2018 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002019 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002020 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002021 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002022 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2023
2024 if (TypeParm)
2025 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002026
Anders Carlsson90036dc2009-06-16 00:30:48 +00002027 if (Name) {
2028 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00002029 TypeParm = new (*this, TypeAlignment)
2030 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002031
2032 TemplateTypeParmType *TypeCheck
2033 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2034 assert(!TypeCheck && "Template type parameter canonical type broken");
2035 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002036 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002037 TypeParm = new (*this, TypeAlignment)
2038 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002039
2040 Types.push_back(TypeParm);
2041 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2042
2043 return QualType(TypeParm, 0);
2044}
2045
John McCalle78aac42010-03-10 03:28:59 +00002046TypeSourceInfo *
2047ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2048 SourceLocation NameLoc,
2049 const TemplateArgumentListInfo &Args,
2050 QualType CanonType) {
2051 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2052
2053 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2054 TemplateSpecializationTypeLoc TL
2055 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2056 TL.setTemplateNameLoc(NameLoc);
2057 TL.setLAngleLoc(Args.getLAngleLoc());
2058 TL.setRAngleLoc(Args.getRAngleLoc());
2059 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2060 TL.setArgLocInfo(i, Args[i].getLocInfo());
2061 return DI;
2062}
2063
Mike Stump11289f42009-09-09 15:08:12 +00002064QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002065ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002066 const TemplateArgumentListInfo &Args,
John McCall0ad16662009-10-29 08:12:44 +00002067 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00002068 unsigned NumArgs = Args.size();
2069
John McCall0ad16662009-10-29 08:12:44 +00002070 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2071 ArgVec.reserve(NumArgs);
2072 for (unsigned i = 0; i != NumArgs; ++i)
2073 ArgVec.push_back(Args[i].getArgument());
2074
2075 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2076}
2077
2078QualType
2079ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002080 const TemplateArgument *Args,
2081 unsigned NumArgs,
2082 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00002083 if (!Canon.isNull())
2084 Canon = getCanonicalType(Canon);
2085 else {
2086 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002087 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2088 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2089 CanonArgs.reserve(NumArgs);
2090 for (unsigned I = 0; I != NumArgs; ++I)
2091 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2092
2093 // Determine whether this canonical template specialization type already
2094 // exists.
2095 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002096 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00002097 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002098
2099 void *InsertPos = 0;
2100 TemplateSpecializationType *Spec
2101 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregora8e02e72009-07-28 23:00:59 +00002103 if (!Spec) {
2104 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00002105 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00002106 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002107 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002108 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00002109 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00002110 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002111 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002112 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002113 }
Mike Stump11289f42009-09-09 15:08:12 +00002114
Douglas Gregor15301382009-07-30 17:40:51 +00002115 if (Canon.isNull())
2116 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002117 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00002118 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00002119 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002120
Douglas Gregora8e02e72009-07-28 23:00:59 +00002121 // Allocate the (non-canonical) template specialization type, but don't
2122 // try to unique it: these types typically have location information that
2123 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002124 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002125 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002126 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002127 TemplateSpecializationType *Spec
2128 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002129 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002130
Douglas Gregor8bf42052009-02-09 18:46:07 +00002131 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002132 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002133}
2134
Mike Stump11289f42009-09-09 15:08:12 +00002135QualType
Douglas Gregorf21eb492009-03-26 23:50:42 +00002136ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor52537682009-03-19 00:18:19 +00002137 QualType NamedType) {
2138 llvm::FoldingSetNodeID ID;
Douglas Gregorf21eb492009-03-26 23:50:42 +00002139 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002140
2141 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002142 QualifiedNameType *T
Douglas Gregor52537682009-03-19 00:18:19 +00002143 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2144 if (T)
2145 return QualType(T, 0);
2146
Douglas Gregorc42075a2010-02-04 18:10:26 +00002147 QualType Canon = NamedType;
2148 if (!Canon.isCanonical()) {
2149 Canon = getCanonicalType(NamedType);
2150 QualifiedNameType *CheckT
2151 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2152 assert(!CheckT && "Qualified name canonical type broken");
2153 (void)CheckT;
2154 }
2155
2156 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002157 Types.push_back(T);
2158 QualifiedNameTypes.InsertNode(T, InsertPos);
2159 return QualType(T, 0);
2160}
2161
Mike Stump11289f42009-09-09 15:08:12 +00002162QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor333489b2009-03-27 23:10:48 +00002163 const IdentifierInfo *Name,
2164 QualType Canon) {
2165 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2166
2167 if (Canon.isNull()) {
2168 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2169 if (CanonNNS != NNS)
2170 Canon = getTypenameType(CanonNNS, Name);
2171 }
2172
2173 llvm::FoldingSetNodeID ID;
2174 TypenameType::Profile(ID, NNS, Name);
2175
2176 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002177 TypenameType *T
Douglas Gregor333489b2009-03-27 23:10:48 +00002178 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2179 if (T)
2180 return QualType(T, 0);
2181
2182 T = new (*this) TypenameType(NNS, Name, Canon);
2183 Types.push_back(T);
2184 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002185 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002186}
2187
Mike Stump11289f42009-09-09 15:08:12 +00002188QualType
2189ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregordce2b622009-04-01 00:28:59 +00002190 const TemplateSpecializationType *TemplateId,
2191 QualType Canon) {
2192 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2193
Douglas Gregorc42075a2010-02-04 18:10:26 +00002194 llvm::FoldingSetNodeID ID;
2195 TypenameType::Profile(ID, NNS, TemplateId);
2196
2197 void *InsertPos = 0;
2198 TypenameType *T
2199 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2200 if (T)
2201 return QualType(T, 0);
2202
Douglas Gregordce2b622009-04-01 00:28:59 +00002203 if (Canon.isNull()) {
2204 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2205 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2206 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2207 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00002208 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00002209 assert(CanonTemplateId &&
2210 "Canonical type must also be a template specialization type");
2211 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2212 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00002213
2214 TypenameType *CheckT
2215 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00002217 }
2218
Douglas Gregordce2b622009-04-01 00:28:59 +00002219 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2220 Types.push_back(T);
2221 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002222 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002223}
2224
John McCallfcc33b02009-09-05 00:15:47 +00002225QualType
2226ASTContext::getElaboratedType(QualType UnderlyingType,
2227 ElaboratedType::TagKind Tag) {
2228 llvm::FoldingSetNodeID ID;
2229 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00002230
John McCallfcc33b02009-09-05 00:15:47 +00002231 void *InsertPos = 0;
2232 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2233 if (T)
2234 return QualType(T, 0);
2235
Douglas Gregorc42075a2010-02-04 18:10:26 +00002236 QualType Canon = UnderlyingType;
2237 if (!Canon.isCanonical()) {
2238 Canon = getCanonicalType(Canon);
2239 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2240 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2241 }
John McCallfcc33b02009-09-05 00:15:47 +00002242
2243 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2244 Types.push_back(T);
2245 ElaboratedTypes.InsertNode(T, InsertPos);
2246 return QualType(T, 0);
2247}
2248
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002249/// CmpProtocolNames - Comparison predicate for sorting protocols
2250/// alphabetically.
2251static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2252 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002253 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002254}
2255
John McCallfc93cf92009-10-22 22:37:11 +00002256static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2257 unsigned NumProtocols) {
2258 if (NumProtocols == 0) return true;
2259
2260 for (unsigned i = 1; i != NumProtocols; ++i)
2261 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2262 return false;
2263 return true;
2264}
2265
2266static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002267 unsigned &NumProtocols) {
2268 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002270 // Sort protocols, keyed by name.
2271 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2272
2273 // Remove duplicates.
2274 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2275 NumProtocols = ProtocolsEnd-Protocols;
2276}
2277
Steve Narofffb4330f2009-06-17 22:40:22 +00002278/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2279/// the given interface decl and the conforming protocol list.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002280QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump11289f42009-09-09 15:08:12 +00002281 ObjCProtocolDecl **Protocols,
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002282 unsigned NumProtocols,
2283 unsigned Quals) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002284 llvm::FoldingSetNodeID ID;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002285 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002286 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Narofffb4330f2009-06-17 22:40:22 +00002287
2288 void *InsertPos = 0;
2289 if (ObjCObjectPointerType *QT =
2290 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002291 return getQualifiedType(QualType(QT, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002292
John McCallfc93cf92009-10-22 22:37:11 +00002293 // Sort the protocol list alphabetically to canonicalize it.
2294 QualType Canonical;
2295 if (!InterfaceT.isCanonical() ||
2296 !areSortedAndUniqued(Protocols, NumProtocols)) {
2297 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2298 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2299 unsigned UniqueCount = NumProtocols;
2300
2301 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2302 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2303
2304 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2305 &Sorted[0], UniqueCount);
2306 } else {
2307 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2308 Protocols, NumProtocols);
2309 }
2310
2311 // Regenerate InsertPos.
2312 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2313 }
2314
Douglas Gregorf85bee62010-02-08 22:59:26 +00002315 // No match.
2316 unsigned Size = sizeof(ObjCObjectPointerType)
2317 + NumProtocols * sizeof(ObjCProtocolDecl *);
2318 void *Mem = Allocate(Size, TypeAlignment);
2319 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2320 InterfaceT,
2321 Protocols,
2322 NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002323
Steve Narofffb4330f2009-06-17 22:40:22 +00002324 Types.push_back(QType);
2325 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002326 return getQualifiedType(QualType(QType, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002327}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002328
Steve Naroffc277ad12009-07-18 15:33:26 +00002329/// getObjCInterfaceType - Return the unique reference to the type for the
2330/// specified ObjC interface decl. The list of protocols is optional.
2331QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002332 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002333 llvm::FoldingSetNodeID ID;
Steve Naroffc277ad12009-07-18 15:33:26 +00002334 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002335
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002336 void *InsertPos = 0;
Steve Naroffc277ad12009-07-18 15:33:26 +00002337 if (ObjCInterfaceType *QT =
2338 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002339 return QualType(QT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002340
John McCallfc93cf92009-10-22 22:37:11 +00002341 // Sort the protocol list alphabetically to canonicalize it.
2342 QualType Canonical;
2343 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2344 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2345 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2346
2347 unsigned UniqueCount = NumProtocols;
2348 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2349
2350 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2351
2352 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2353 }
2354
Douglas Gregorf85bee62010-02-08 22:59:26 +00002355 unsigned Size = sizeof(ObjCInterfaceType)
2356 + NumProtocols * sizeof(ObjCProtocolDecl *);
2357 void *Mem = Allocate(Size, TypeAlignment);
2358 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2359 const_cast<ObjCInterfaceDecl*>(Decl),
2360 Protocols,
2361 NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002362
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002363 Types.push_back(QType);
Steve Naroffc277ad12009-07-18 15:33:26 +00002364 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002365 return QualType(QType, 0);
2366}
2367
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002368/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2369/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002370/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002371/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002372/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002373QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002374 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002375 if (tofExpr->isTypeDependent()) {
2376 llvm::FoldingSetNodeID ID;
2377 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002379 void *InsertPos = 0;
2380 DependentTypeOfExprType *Canon
2381 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2382 if (Canon) {
2383 // We already have a "canonical" version of an identical, dependent
2384 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002385 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002386 QualType((TypeOfExprType*)Canon, 0));
2387 }
2388 else {
2389 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002390 Canon
2391 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002392 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2393 toe = Canon;
2394 }
2395 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002396 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002397 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002398 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002399 Types.push_back(toe);
2400 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002401}
2402
Steve Naroffa773cd52007-08-01 18:02:17 +00002403/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2404/// TypeOfType AST's. The only motivation to unique these nodes would be
2405/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002406/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002407/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002408QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002409 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002410 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002411 Types.push_back(tot);
2412 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002413}
2414
Anders Carlssonad6bd352009-06-24 21:24:56 +00002415/// getDecltypeForExpr - Given an expr, will return the decltype for that
2416/// expression, according to the rules in C++0x [dcl.type.simple]p4
2417static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002418 if (e->isTypeDependent())
2419 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002420
Anders Carlssonad6bd352009-06-24 21:24:56 +00002421 // If e is an id expression or a class member access, decltype(e) is defined
2422 // as the type of the entity named by e.
2423 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2424 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2425 return VD->getType();
2426 }
2427 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2428 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2429 return FD->getType();
2430 }
2431 // If e is a function call or an invocation of an overloaded operator,
2432 // (parentheses around e are ignored), decltype(e) is defined as the
2433 // return type of that function.
2434 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2435 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002436
Anders Carlssonad6bd352009-06-24 21:24:56 +00002437 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002438
2439 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002440 // defined as T&, otherwise decltype(e) is defined as T.
2441 if (e->isLvalue(Context) == Expr::LV_Valid)
2442 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002443
Anders Carlssonad6bd352009-06-24 21:24:56 +00002444 return T;
2445}
2446
Anders Carlsson81df7b82009-06-24 19:06:50 +00002447/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2448/// DecltypeType AST's. The only motivation to unique these nodes would be
2449/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002450/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002451/// on canonical type's (which are always unique).
2452QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002453 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002454 if (e->isTypeDependent()) {
2455 llvm::FoldingSetNodeID ID;
2456 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002457
Douglas Gregora21f6c32009-07-30 23:36:40 +00002458 void *InsertPos = 0;
2459 DependentDecltypeType *Canon
2460 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2461 if (Canon) {
2462 // We already have a "canonical" version of an equivalent, dependent
2463 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002464 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002465 QualType((DecltypeType*)Canon, 0));
2466 }
2467 else {
2468 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002469 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002470 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2471 dt = Canon;
2472 }
2473 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002474 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002475 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002476 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002477 Types.push_back(dt);
2478 return QualType(dt, 0);
2479}
2480
Chris Lattnerfb072462007-01-23 05:45:31 +00002481/// getTagDeclType - Return the unique reference to the type for the
2482/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002483QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002484 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002485 // FIXME: What is the design on getTagDeclType when it requires casting
2486 // away const? mutable?
2487 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002488}
2489
Mike Stump11289f42009-09-09 15:08:12 +00002490/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2491/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2492/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002493CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002494 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002495}
Chris Lattnerfb072462007-01-23 05:45:31 +00002496
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002497/// getSignedWCharType - Return the type of "signed wchar_t".
2498/// Used when in C++, as a GCC extension.
2499QualType ASTContext::getSignedWCharType() const {
2500 // FIXME: derive from "Target" ?
2501 return WCharTy;
2502}
2503
2504/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2505/// Used when in C++, as a GCC extension.
2506QualType ASTContext::getUnsignedWCharType() const {
2507 // FIXME: derive from "Target" ?
2508 return UnsignedIntTy;
2509}
2510
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002511/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2512/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2513QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002514 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002515}
2516
Chris Lattnera21ad802008-04-02 05:18:44 +00002517//===----------------------------------------------------------------------===//
2518// Type Operators
2519//===----------------------------------------------------------------------===//
2520
John McCallfc93cf92009-10-22 22:37:11 +00002521CanQualType ASTContext::getCanonicalParamType(QualType T) {
2522 // Push qualifiers into arrays, and then discard any remaining
2523 // qualifiers.
2524 T = getCanonicalType(T);
2525 const Type *Ty = T.getTypePtr();
2526
2527 QualType Result;
2528 if (isa<ArrayType>(Ty)) {
2529 Result = getArrayDecayedType(QualType(Ty,0));
2530 } else if (isa<FunctionType>(Ty)) {
2531 Result = getPointerType(QualType(Ty, 0));
2532 } else {
2533 Result = QualType(Ty, 0);
2534 }
2535
2536 return CanQualType::CreateUnsafe(Result);
2537}
2538
Chris Lattnered0d0792008-04-06 22:41:35 +00002539/// getCanonicalType - Return the canonical (structural) type corresponding to
2540/// the specified potentially non-canonical type. The non-canonical version
2541/// of a type may have many "decorated" versions of types. Decorators can
2542/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2543/// to be free of any of these, allowing two canonical types to be compared
2544/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002545CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002546 QualifierCollector Quals;
2547 const Type *Ptr = Quals.strip(T);
2548 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002549
John McCall8ccfcb52009-09-24 19:53:00 +00002550 // The canonical internal type will be the canonical type *except*
2551 // that we push type qualifiers down through array types.
2552
2553 // If there are no new qualifiers to push down, stop here.
2554 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002555 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002556
John McCall8ccfcb52009-09-24 19:53:00 +00002557 // If the type qualifiers are on an array type, get the canonical
2558 // type of the array with the qualifiers applied to the element
2559 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002560 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2561 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002562 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002563
Chris Lattner7adf0762008-08-04 07:31:14 +00002564 // Get the canonical version of the element with the extra qualifiers on it.
2565 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002566 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002567 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002568
Chris Lattner7adf0762008-08-04 07:31:14 +00002569 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002570 return CanQualType::CreateUnsafe(
2571 getConstantArrayType(NewEltTy, CAT->getSize(),
2572 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002573 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002574 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002575 return CanQualType::CreateUnsafe(
2576 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002577 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregor4619e432008-12-05 23:32:09 +00002579 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002580 return CanQualType::CreateUnsafe(
2581 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002582 DSAT->getSizeExpr() ?
2583 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002584 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002585 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002586 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002587
Chris Lattner7adf0762008-08-04 07:31:14 +00002588 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002589 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002590 VAT->getSizeExpr() ?
2591 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002592 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002593 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002594 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002595}
2596
Chandler Carruth607f38e2009-12-29 07:16:59 +00002597QualType ASTContext::getUnqualifiedArrayType(QualType T,
2598 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002599 Quals = T.getQualifiers();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002600 if (!isa<ArrayType>(T)) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002601 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002602 }
2603
Chandler Carruth607f38e2009-12-29 07:16:59 +00002604 const ArrayType *AT = cast<ArrayType>(T);
2605 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002606 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002607 if (Elt == UnqualElt)
2608 return T;
2609
2610 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2611 return getConstantArrayType(UnqualElt, CAT->getSize(),
2612 CAT->getSizeModifier(), 0);
2613 }
2614
2615 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2616 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2617 }
2618
2619 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2620 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2621 DSAT->getSizeModifier(), 0,
2622 SourceRange());
2623}
2624
John McCall847e2a12009-11-24 18:42:40 +00002625DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2626 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2627 return TD->getDeclName();
2628
2629 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2630 if (DTN->isIdentifier()) {
2631 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2632 } else {
2633 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2634 }
2635 }
2636
John McCalld28ae272009-12-02 08:04:21 +00002637 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2638 assert(Storage);
2639 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002640}
2641
Douglas Gregor6bc50582009-05-07 06:41:52 +00002642TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2643 // If this template name refers to a template, the canonical
2644 // template name merely stores the template itself.
2645 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002646 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002647
John McCalld28ae272009-12-02 08:04:21 +00002648 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002649
Douglas Gregor6bc50582009-05-07 06:41:52 +00002650 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2651 assert(DTN && "Non-dependent template names must refer to template decls.");
2652 return DTN->CanonicalTemplateName;
2653}
2654
Douglas Gregoradee3e32009-11-11 23:06:43 +00002655bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2656 X = getCanonicalTemplateName(X);
2657 Y = getCanonicalTemplateName(Y);
2658 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2659}
2660
Mike Stump11289f42009-09-09 15:08:12 +00002661TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002662ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2663 switch (Arg.getKind()) {
2664 case TemplateArgument::Null:
2665 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002666
Douglas Gregora8e02e72009-07-28 23:00:59 +00002667 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002668 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002669
Douglas Gregora8e02e72009-07-28 23:00:59 +00002670 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002671 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002672
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002673 case TemplateArgument::Template:
2674 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2675
Douglas Gregora8e02e72009-07-28 23:00:59 +00002676 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002677 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002678 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002679
Douglas Gregora8e02e72009-07-28 23:00:59 +00002680 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002681 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002682
Douglas Gregora8e02e72009-07-28 23:00:59 +00002683 case TemplateArgument::Pack: {
2684 // FIXME: Allocate in ASTContext
2685 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2686 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002687 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002688 AEnd = Arg.pack_end();
2689 A != AEnd; (void)++A, ++Idx)
2690 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002691
Douglas Gregora8e02e72009-07-28 23:00:59 +00002692 TemplateArgument Result;
2693 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2694 return Result;
2695 }
2696 }
2697
2698 // Silence GCC warning
2699 assert(false && "Unhandled template argument kind");
2700 return TemplateArgument();
2701}
2702
Douglas Gregor333489b2009-03-27 23:10:48 +00002703NestedNameSpecifier *
2704ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002705 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002706 return 0;
2707
2708 switch (NNS->getKind()) {
2709 case NestedNameSpecifier::Identifier:
2710 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002711 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002712 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2713 NNS->getAsIdentifier());
2714
2715 case NestedNameSpecifier::Namespace:
2716 // A namespace is canonical; build a nested-name-specifier with
2717 // this namespace and no prefix.
2718 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2719
2720 case NestedNameSpecifier::TypeSpec:
2721 case NestedNameSpecifier::TypeSpecWithTemplate: {
2722 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002723 return NestedNameSpecifier::Create(*this, 0,
2724 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002725 T.getTypePtr());
2726 }
2727
2728 case NestedNameSpecifier::Global:
2729 // The global specifier is canonical and unique.
2730 return NNS;
2731 }
2732
2733 // Required to silence a GCC warning
2734 return 0;
2735}
2736
Chris Lattner7adf0762008-08-04 07:31:14 +00002737
2738const ArrayType *ASTContext::getAsArrayType(QualType T) {
2739 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002740 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002741 // Handle the common positive case fast.
2742 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2743 return AT;
2744 }
Mike Stump11289f42009-09-09 15:08:12 +00002745
John McCall8ccfcb52009-09-24 19:53:00 +00002746 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002747 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002748 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002749 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002750
John McCall8ccfcb52009-09-24 19:53:00 +00002751 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002752 // implements C99 6.7.3p8: "If the specification of an array type includes
2753 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002754
Chris Lattner7adf0762008-08-04 07:31:14 +00002755 // If we get here, we either have type qualifiers on the type, or we have
2756 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002757 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002758
John McCall8ccfcb52009-09-24 19:53:00 +00002759 QualifierCollector Qs;
2760 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattner7adf0762008-08-04 07:31:14 +00002762 // If we have a simple case, just return now.
2763 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002764 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002765 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattner7adf0762008-08-04 07:31:14 +00002767 // Otherwise, we have an array and we have qualifiers on it. Push the
2768 // qualifiers into the array element type and return a new array type.
2769 // Get the canonical version of the element with the extra qualifiers on it.
2770 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002771 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattner7adf0762008-08-04 07:31:14 +00002773 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2774 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2775 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002776 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002777 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2778 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2779 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002780 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002781
Mike Stump11289f42009-09-09 15:08:12 +00002782 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002783 = dyn_cast<DependentSizedArrayType>(ATy))
2784 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002785 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002786 DSAT->getSizeExpr() ?
2787 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002788 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002789 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002790 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002791
Chris Lattner7adf0762008-08-04 07:31:14 +00002792 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002793 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002794 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002795 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002796 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002797 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002798 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002799}
2800
2801
Chris Lattnera21ad802008-04-02 05:18:44 +00002802/// getArrayDecayedType - Return the properly qualified result of decaying the
2803/// specified array type to a pointer. This operation is non-trivial when
2804/// handling typedefs etc. The canonical type of "T" must be an array type,
2805/// this returns a pointer to a properly qualified element of the array.
2806///
2807/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2808QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002809 // Get the element type with 'getAsArrayType' so that we don't lose any
2810 // typedefs in the element type of the array. This also handles propagation
2811 // of type qualifiers from the array type into the element type if present
2812 // (C99 6.7.3p8).
2813 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2814 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002815
Chris Lattner7adf0762008-08-04 07:31:14 +00002816 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002817
2818 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002819 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002820}
2821
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002822QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002823 QualifierCollector Qs;
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002824 while (true) {
John McCall8ccfcb52009-09-24 19:53:00 +00002825 const Type *UT = Qs.strip(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002826 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2827 QT = AT->getElementType();
Mike Stumpea086c72009-07-25 23:24:03 +00002828 } else {
John McCall8ccfcb52009-09-24 19:53:00 +00002829 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002830 }
2831 }
2832}
2833
Anders Carlsson4bf82142009-09-25 01:23:32 +00002834QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2835 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002836
Anders Carlsson4bf82142009-09-25 01:23:32 +00002837 if (const ArrayType *AT = getAsArrayType(ElemTy))
2838 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002839
Anders Carlssone0808df2008-12-21 03:44:36 +00002840 return ElemTy;
2841}
2842
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002843/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002844uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002845ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2846 uint64_t ElementCount = 1;
2847 do {
2848 ElementCount *= CA->getSize().getZExtValue();
2849 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2850 } while (CA);
2851 return ElementCount;
2852}
2853
Steve Naroff0af91202007-04-27 21:51:21 +00002854/// getFloatingRank - Return a relative rank for floating point types.
2855/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002856static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002857 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002858 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002859
John McCall9dd450b2009-09-21 23:43:11 +00002860 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2861 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002862 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002863 case BuiltinType::Float: return FloatRank;
2864 case BuiltinType::Double: return DoubleRank;
2865 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002866 }
2867}
2868
Mike Stump11289f42009-09-09 15:08:12 +00002869/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2870/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002871/// 'typeDomain' is a real floating point or complex type.
2872/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002873QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2874 QualType Domain) const {
2875 FloatingRank EltRank = getFloatingRank(Size);
2876 if (Domain->isComplexType()) {
2877 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002878 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002879 case FloatRank: return FloatComplexTy;
2880 case DoubleRank: return DoubleComplexTy;
2881 case LongDoubleRank: return LongDoubleComplexTy;
2882 }
Steve Naroff0af91202007-04-27 21:51:21 +00002883 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002884
2885 assert(Domain->isRealFloatingType() && "Unknown domain!");
2886 switch (EltRank) {
2887 default: assert(0 && "getFloatingRank(): illegal value for rank");
2888 case FloatRank: return FloatTy;
2889 case DoubleRank: return DoubleTy;
2890 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002891 }
Steve Naroffe4718892007-04-27 18:30:00 +00002892}
2893
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002894/// getFloatingTypeOrder - Compare the rank of the two specified floating
2895/// point types, ignoring the domain of the type (i.e. 'double' ==
2896/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002897/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002898int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2899 FloatingRank LHSR = getFloatingRank(LHS);
2900 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002901
Chris Lattnerb90739d2008-04-06 23:38:49 +00002902 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002903 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002904 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002905 return 1;
2906 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002907}
2908
Chris Lattner76a00cf2008-04-06 22:59:24 +00002909/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2910/// routine will assert if passed a built-in type that isn't an integer or enum,
2911/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002912unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002913 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002914 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002915 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002916
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002917 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2918 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2919
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002920 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2921 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2922
2923 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2924 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2925
Chris Lattner76a00cf2008-04-06 22:59:24 +00002926 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002927 default: assert(0 && "getIntegerRank(): not a built-in integer");
2928 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002929 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002930 case BuiltinType::Char_S:
2931 case BuiltinType::Char_U:
2932 case BuiltinType::SChar:
2933 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002934 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002935 case BuiltinType::Short:
2936 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002937 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002938 case BuiltinType::Int:
2939 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002940 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002941 case BuiltinType::Long:
2942 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002943 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002944 case BuiltinType::LongLong:
2945 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002946 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002947 case BuiltinType::Int128:
2948 case BuiltinType::UInt128:
2949 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002950 }
2951}
2952
Eli Friedman629ffb92009-08-20 04:21:42 +00002953/// \brief Whether this is a promotable bitfield reference according
2954/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2955///
2956/// \returns the type this bit-field will promote to, or NULL if no
2957/// promotion occurs.
2958QualType ASTContext::isPromotableBitField(Expr *E) {
2959 FieldDecl *Field = E->getBitField();
2960 if (!Field)
2961 return QualType();
2962
2963 QualType FT = Field->getType();
2964
2965 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2966 uint64_t BitWidth = BitWidthAP.getZExtValue();
2967 uint64_t IntSize = getTypeSize(IntTy);
2968 // GCC extension compatibility: if the bit-field size is less than or equal
2969 // to the size of int, it gets promoted no matter what its type is.
2970 // For instance, unsigned long bf : 4 gets promoted to signed int.
2971 if (BitWidth < IntSize)
2972 return IntTy;
2973
2974 if (BitWidth == IntSize)
2975 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2976
2977 // Types bigger than int are not subject to promotions, and therefore act
2978 // like the base type.
2979 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2980 // is ridiculous.
2981 return QualType();
2982}
2983
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002984/// getPromotedIntegerType - Returns the type that Promotable will
2985/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2986/// integer type.
2987QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2988 assert(!Promotable.isNull());
2989 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002990 if (const EnumType *ET = Promotable->getAs<EnumType>())
2991 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002992 if (Promotable->isSignedIntegerType())
2993 return IntTy;
2994 uint64_t PromotableSize = getTypeSize(Promotable);
2995 uint64_t IntSize = getTypeSize(IntTy);
2996 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2997 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2998}
2999
Mike Stump11289f42009-09-09 15:08:12 +00003000/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003001/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003002/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003003int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003004 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3005 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003006 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003007
Chris Lattner76a00cf2008-04-06 22:59:24 +00003008 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3009 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003010
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003011 unsigned LHSRank = getIntegerRank(LHSC);
3012 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003014 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3015 if (LHSRank == RHSRank) return 0;
3016 return LHSRank > RHSRank ? 1 : -1;
3017 }
Mike Stump11289f42009-09-09 15:08:12 +00003018
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003019 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3020 if (LHSUnsigned) {
3021 // If the unsigned [LHS] type is larger, return it.
3022 if (LHSRank >= RHSRank)
3023 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003024
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003025 // If the signed type can represent all values of the unsigned type, it
3026 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003027 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003028 return -1;
3029 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003030
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003031 // If the unsigned [RHS] type is larger, return it.
3032 if (RHSRank >= LHSRank)
3033 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003034
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003035 // If the signed type can represent all values of the unsigned type, it
3036 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003037 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003038 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003039}
Anders Carlsson98f07902007-08-17 05:31:46 +00003040
Anders Carlsson6d417272009-11-14 21:45:58 +00003041static RecordDecl *
3042CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3043 SourceLocation L, IdentifierInfo *Id) {
3044 if (Ctx.getLangOptions().CPlusPlus)
3045 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3046 else
3047 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3048}
3049
Mike Stump11289f42009-09-09 15:08:12 +00003050// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00003051QualType ASTContext::getCFConstantStringType() {
3052 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003053 CFConstantStringTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003054 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3055 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003056 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003057
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003058 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003059
Anders Carlsson98f07902007-08-17 05:31:46 +00003060 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003061 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003062 // int flags;
3063 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003064 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003065 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003066 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003067 FieldTypes[3] = LongTy;
3068
Anders Carlsson98f07902007-08-17 05:31:46 +00003069 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003070 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003071 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003072 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003073 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003074 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003075 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003076 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003077 }
3078
Douglas Gregord5058122010-02-11 01:19:42 +00003079 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003080 }
Mike Stump11289f42009-09-09 15:08:12 +00003081
Anders Carlsson98f07902007-08-17 05:31:46 +00003082 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003083}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003084
Douglas Gregor512b0772009-04-23 22:29:11 +00003085void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003086 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003087 assert(Rec && "Invalid CFConstantStringType");
3088 CFConstantStringTypeDecl = Rec->getDecl();
3089}
3090
Mike Stump11289f42009-09-09 15:08:12 +00003091QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003092 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003093 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003094 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3095 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003096 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003097
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003098 QualType FieldTypes[] = {
3099 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003100 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003101 getPointerType(UnsignedLongTy),
3102 getConstantArrayType(UnsignedLongTy,
3103 llvm::APInt(32, 5), ArrayType::Normal, 0)
3104 };
Mike Stump11289f42009-09-09 15:08:12 +00003105
Douglas Gregor91f84212008-12-11 16:49:14 +00003106 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003107 FieldDecl *Field = FieldDecl::Create(*this,
3108 ObjCFastEnumerationStateTypeDecl,
3109 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003110 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003111 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003112 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003113 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003114 }
Mike Stump11289f42009-09-09 15:08:12 +00003115
Douglas Gregord5058122010-02-11 01:19:42 +00003116 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003117 }
Mike Stump11289f42009-09-09 15:08:12 +00003118
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003119 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3120}
3121
Mike Stumpd0153282009-10-20 02:12:22 +00003122QualType ASTContext::getBlockDescriptorType() {
3123 if (BlockDescriptorType)
3124 return getTagDeclType(BlockDescriptorType);
3125
3126 RecordDecl *T;
3127 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003128 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3129 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003130 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003131
3132 QualType FieldTypes[] = {
3133 UnsignedLongTy,
3134 UnsignedLongTy,
3135 };
3136
3137 const char *FieldNames[] = {
3138 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003139 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003140 };
3141
3142 for (size_t i = 0; i < 2; ++i) {
3143 FieldDecl *Field = FieldDecl::Create(*this,
3144 T,
3145 SourceLocation(),
3146 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003147 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003148 /*BitWidth=*/0,
3149 /*Mutable=*/false);
3150 T->addDecl(Field);
3151 }
3152
Douglas Gregord5058122010-02-11 01:19:42 +00003153 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003154
3155 BlockDescriptorType = T;
3156
3157 return getTagDeclType(BlockDescriptorType);
3158}
3159
3160void ASTContext::setBlockDescriptorType(QualType T) {
3161 const RecordType *Rec = T->getAs<RecordType>();
3162 assert(Rec && "Invalid BlockDescriptorType");
3163 BlockDescriptorType = Rec->getDecl();
3164}
3165
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003166QualType ASTContext::getBlockDescriptorExtendedType() {
3167 if (BlockDescriptorExtendedType)
3168 return getTagDeclType(BlockDescriptorExtendedType);
3169
3170 RecordDecl *T;
3171 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003172 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3173 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003174 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003175
3176 QualType FieldTypes[] = {
3177 UnsignedLongTy,
3178 UnsignedLongTy,
3179 getPointerType(VoidPtrTy),
3180 getPointerType(VoidPtrTy)
3181 };
3182
3183 const char *FieldNames[] = {
3184 "reserved",
3185 "Size",
3186 "CopyFuncPtr",
3187 "DestroyFuncPtr"
3188 };
3189
3190 for (size_t i = 0; i < 4; ++i) {
3191 FieldDecl *Field = FieldDecl::Create(*this,
3192 T,
3193 SourceLocation(),
3194 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003195 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003196 /*BitWidth=*/0,
3197 /*Mutable=*/false);
3198 T->addDecl(Field);
3199 }
3200
Douglas Gregord5058122010-02-11 01:19:42 +00003201 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003202
3203 BlockDescriptorExtendedType = T;
3204
3205 return getTagDeclType(BlockDescriptorExtendedType);
3206}
3207
3208void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3209 const RecordType *Rec = T->getAs<RecordType>();
3210 assert(Rec && "Invalid BlockDescriptorType");
3211 BlockDescriptorExtendedType = Rec->getDecl();
3212}
3213
Mike Stump94967902009-10-21 18:16:27 +00003214bool ASTContext::BlockRequiresCopying(QualType Ty) {
3215 if (Ty->isBlockPointerType())
3216 return true;
3217 if (isObjCNSObjectType(Ty))
3218 return true;
3219 if (Ty->isObjCObjectPointerType())
3220 return true;
3221 return false;
3222}
3223
3224QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3225 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003226 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003227 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003228 // unsigned int __flags;
3229 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003230 // void *__copy_helper; // as needed
3231 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003232 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003233 // } *
3234
Mike Stump94967902009-10-21 18:16:27 +00003235 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3236
3237 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003238 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003239 llvm::SmallString<36> Name;
3240 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3241 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003242 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003243 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3244 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003245 T->startDefinition();
3246 QualType Int32Ty = IntTy;
3247 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3248 QualType FieldTypes[] = {
3249 getPointerType(VoidPtrTy),
3250 getPointerType(getTagDeclType(T)),
3251 Int32Ty,
3252 Int32Ty,
3253 getPointerType(VoidPtrTy),
3254 getPointerType(VoidPtrTy),
3255 Ty
3256 };
3257
3258 const char *FieldNames[] = {
3259 "__isa",
3260 "__forwarding",
3261 "__flags",
3262 "__size",
3263 "__copy_helper",
3264 "__destroy_helper",
3265 DeclName,
3266 };
3267
3268 for (size_t i = 0; i < 7; ++i) {
3269 if (!HasCopyAndDispose && i >=4 && i <= 5)
3270 continue;
3271 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3272 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003273 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003274 /*BitWidth=*/0, /*Mutable=*/false);
3275 T->addDecl(Field);
3276 }
3277
Douglas Gregord5058122010-02-11 01:19:42 +00003278 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003279
3280 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003281}
3282
3283
3284QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003285 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003286 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003287 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003288 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003289 llvm::SmallString<36> Name;
3290 llvm::raw_svector_ostream(Name) << "__block_literal_"
3291 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003292 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003293 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3294 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003295 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003296 QualType FieldTypes[] = {
3297 getPointerType(VoidPtrTy),
3298 IntTy,
3299 IntTy,
3300 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003301 (BlockHasCopyDispose ?
3302 getPointerType(getBlockDescriptorExtendedType()) :
3303 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003304 };
3305
3306 const char *FieldNames[] = {
3307 "__isa",
3308 "__flags",
3309 "__reserved",
3310 "__FuncPtr",
3311 "__descriptor"
3312 };
3313
3314 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003315 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003316 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003317 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003318 /*BitWidth=*/0, /*Mutable=*/false);
3319 T->addDecl(Field);
3320 }
3321
3322 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3323 const Expr *E = BlockDeclRefDecls[i];
3324 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3325 clang::IdentifierInfo *Name = 0;
3326 if (BDRE) {
3327 const ValueDecl *D = BDRE->getDecl();
3328 Name = &Idents.get(D->getName());
3329 }
3330 QualType FieldType = E->getType();
3331
3332 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003333 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3334 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003335
3336 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003337 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003338 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpd0153282009-10-20 02:12:22 +00003339 T->addDecl(Field);
3340 }
3341
Douglas Gregord5058122010-02-11 01:19:42 +00003342 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003343
3344 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003345}
3346
Douglas Gregor512b0772009-04-23 22:29:11 +00003347void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003348 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003349 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3350 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3351}
3352
Anders Carlsson18acd442007-10-29 06:33:42 +00003353// This returns true if a type has been typedefed to BOOL:
3354// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003355static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003356 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003357 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3358 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003359
Anders Carlssond8499822007-10-29 05:01:08 +00003360 return false;
3361}
3362
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003363/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003364/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003365CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003366 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003367
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003368 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003369 if (sz.isPositive() && type->isIntegralType())
3370 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003371 // Treat arrays as pointers, since that's how they're passed in.
3372 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003373 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003374 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003375}
3376
3377static inline
3378std::string charUnitsToString(const CharUnits &CU) {
3379 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003380}
3381
David Chisnall950a9512009-11-17 19:33:30 +00003382/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3383/// declaration.
3384void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3385 std::string& S) {
3386 const BlockDecl *Decl = Expr->getBlockDecl();
3387 QualType BlockTy =
3388 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3389 // Encode result type.
3390 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3391 // Compute size of all parameters.
3392 // Start with computing size of a pointer in number of bytes.
3393 // FIXME: There might(should) be a better way of doing this computation!
3394 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003395 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3396 CharUnits ParmOffset = PtrSize;
David Chisnall950a9512009-11-17 19:33:30 +00003397 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3398 E = Decl->param_end(); PI != E; ++PI) {
3399 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003400 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003401 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003402 ParmOffset += sz;
3403 }
3404 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003405 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003406 // Block pointer and offset.
3407 S += "@?0";
3408 ParmOffset = PtrSize;
3409
3410 // Argument types.
3411 ParmOffset = PtrSize;
3412 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3413 Decl->param_end(); PI != E; ++PI) {
3414 ParmVarDecl *PVDecl = *PI;
3415 QualType PType = PVDecl->getOriginalType();
3416 if (const ArrayType *AT =
3417 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3418 // Use array's original type only if it has known number of
3419 // elements.
3420 if (!isa<ConstantArrayType>(AT))
3421 PType = PVDecl->getType();
3422 } else if (PType->isFunctionType())
3423 PType = PVDecl->getType();
3424 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003425 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003426 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003427 }
3428}
3429
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003430/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003431/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003432void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003433 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003434 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003435 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003436 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003437 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003438 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003439 // Compute size of all parameters.
3440 // Start with computing size of a pointer in number of bytes.
3441 // FIXME: There might(should) be a better way of doing this computation!
3442 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003443 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003444 // The first two arguments (self and _cmd) are pointers; account for
3445 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003446 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003447 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3448 E = Decl->param_end(); PI != E; ++PI) {
3449 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003450 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003451 assert (sz.isPositive() &&
3452 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003453 ParmOffset += sz;
3454 }
Ken Dyck40775002010-01-11 17:06:35 +00003455 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003456 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003457 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003458
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003459 // Argument types.
3460 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003461 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3462 E = Decl->param_end(); PI != E; ++PI) {
3463 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003464 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003465 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003466 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3467 // Use array's original type only if it has known number of
3468 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003469 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003470 PType = PVDecl->getType();
3471 } else if (PType->isFunctionType())
3472 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003473 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003474 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003475 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003476 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003477 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003478 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003479 }
3480}
3481
Daniel Dunbar4932b362008-08-28 04:38:10 +00003482/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003483/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003484/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3485/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003486/// Property attributes are stored as a comma-delimited C string. The simple
3487/// attributes readonly and bycopy are encoded as single characters. The
3488/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3489/// encoded as single characters, followed by an identifier. Property types
3490/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003491/// these attributes are defined by the following enumeration:
3492/// @code
3493/// enum PropertyAttributes {
3494/// kPropertyReadOnly = 'R', // property is read-only.
3495/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3496/// kPropertyByref = '&', // property is a reference to the value last assigned
3497/// kPropertyDynamic = 'D', // property is dynamic
3498/// kPropertyGetter = 'G', // followed by getter selector name
3499/// kPropertySetter = 'S', // followed by setter selector name
3500/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3501/// kPropertyType = 't' // followed by old-style type encoding.
3502/// kPropertyWeak = 'W' // 'weak' property
3503/// kPropertyStrong = 'P' // property GC'able
3504/// kPropertyNonAtomic = 'N' // property non-atomic
3505/// };
3506/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003507void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003508 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003509 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003510 // Collect information from the property implementation decl(s).
3511 bool Dynamic = false;
3512 ObjCPropertyImplDecl *SynthesizePID = 0;
3513
3514 // FIXME: Duplicated code due to poor abstraction.
3515 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003516 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003517 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3518 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003519 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003520 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003521 ObjCPropertyImplDecl *PID = *i;
3522 if (PID->getPropertyDecl() == PD) {
3523 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3524 Dynamic = true;
3525 } else {
3526 SynthesizePID = PID;
3527 }
3528 }
3529 }
3530 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003531 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003532 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003533 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003534 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003535 ObjCPropertyImplDecl *PID = *i;
3536 if (PID->getPropertyDecl() == PD) {
3537 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3538 Dynamic = true;
3539 } else {
3540 SynthesizePID = PID;
3541 }
3542 }
Mike Stump11289f42009-09-09 15:08:12 +00003543 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003544 }
3545 }
3546
3547 // FIXME: This is not very efficient.
3548 S = "T";
3549
3550 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003551 // GCC has some special rules regarding encoding of properties which
3552 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003553 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003554 true /* outermost type */,
3555 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003556
3557 if (PD->isReadOnly()) {
3558 S += ",R";
3559 } else {
3560 switch (PD->getSetterKind()) {
3561 case ObjCPropertyDecl::Assign: break;
3562 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003563 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003564 }
3565 }
3566
3567 // It really isn't clear at all what this means, since properties
3568 // are "dynamic by default".
3569 if (Dynamic)
3570 S += ",D";
3571
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003572 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3573 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003574
Daniel Dunbar4932b362008-08-28 04:38:10 +00003575 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3576 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003577 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003578 }
3579
3580 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3581 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003582 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003583 }
3584
3585 if (SynthesizePID) {
3586 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3587 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003588 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003589 }
3590
3591 // FIXME: OBJCGC: weak & strong
3592}
3593
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003594/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003595/// Another legacy compatibility encoding: 32-bit longs are encoded as
3596/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003597/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3598///
3599void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003600 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003601 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003602 if (BT->getKind() == BuiltinType::ULong &&
3603 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003604 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003605 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003606 if (BT->getKind() == BuiltinType::Long &&
3607 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003608 PointeeTy = IntTy;
3609 }
3610 }
3611}
3612
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003613void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003614 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003615 // We follow the behavior of gcc, expanding structures which are
3616 // directly pointed to, and expanding embedded structures. Note that
3617 // these rules are sufficient to prevent recursive encoding of the
3618 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003619 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003620 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003621}
3622
Mike Stump11289f42009-09-09 15:08:12 +00003623static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003624 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003625 const Expr *E = FD->getBitWidth();
3626 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3627 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003628 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003629 S += 'b';
3630 S += llvm::utostr(N);
3631}
3632
Daniel Dunbar07d07852009-10-18 21:17:35 +00003633// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003634void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3635 bool ExpandPointedToStructures,
3636 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003637 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003638 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003639 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003640 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003641 if (FD && FD->isBitField())
3642 return EncodeBitField(this, S, FD);
3643 char encoding;
3644 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003645 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003646 case BuiltinType::Void: encoding = 'v'; break;
3647 case BuiltinType::Bool: encoding = 'B'; break;
3648 case BuiltinType::Char_U:
3649 case BuiltinType::UChar: encoding = 'C'; break;
3650 case BuiltinType::UShort: encoding = 'S'; break;
3651 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003652 case BuiltinType::ULong:
3653 encoding =
3654 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003655 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003656 case BuiltinType::UInt128: encoding = 'T'; break;
3657 case BuiltinType::ULongLong: encoding = 'Q'; break;
3658 case BuiltinType::Char_S:
3659 case BuiltinType::SChar: encoding = 'c'; break;
3660 case BuiltinType::Short: encoding = 's'; break;
3661 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003662 case BuiltinType::Long:
3663 encoding =
3664 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003665 break;
3666 case BuiltinType::LongLong: encoding = 'q'; break;
3667 case BuiltinType::Int128: encoding = 't'; break;
3668 case BuiltinType::Float: encoding = 'f'; break;
3669 case BuiltinType::Double: encoding = 'd'; break;
3670 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Chris Lattnere7cabb92009-07-13 00:10:46 +00003673 S += encoding;
3674 return;
3675 }
Mike Stump11289f42009-09-09 15:08:12 +00003676
John McCall9dd450b2009-09-21 23:43:11 +00003677 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003678 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003679 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003680 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003681 return;
3682 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003683
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003684 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003685 if (PT->isObjCSelType()) {
3686 S += ':';
3687 return;
3688 }
Anders Carlssond8499822007-10-29 05:01:08 +00003689 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003690
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003691 bool isReadOnly = false;
3692 // For historical/compatibility reasons, the read-only qualifier of the
3693 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3694 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003695 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003696 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003697 if (OutermostType && T.isConstQualified()) {
3698 isReadOnly = true;
3699 S += 'r';
3700 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003701 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003702 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003703 while (P->getAs<PointerType>())
3704 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003705 if (P.isConstQualified()) {
3706 isReadOnly = true;
3707 S += 'r';
3708 }
3709 }
3710 if (isReadOnly) {
3711 // Another legacy compatibility encoding. Some ObjC qualifier and type
3712 // combinations need to be rearranged.
3713 // Rewrite "in const" from "nr" to "rn"
3714 const char * s = S.c_str();
3715 int len = S.length();
3716 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3717 std::string replace = "rn";
3718 S.replace(S.end()-2, S.end(), replace);
3719 }
3720 }
Mike Stump11289f42009-09-09 15:08:12 +00003721
Anders Carlssond8499822007-10-29 05:01:08 +00003722 if (PointeeTy->isCharType()) {
3723 // char pointer types should be encoded as '*' unless it is a
3724 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003725 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003726 S += '*';
3727 return;
3728 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003729 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003730 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3731 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3732 S += '#';
3733 return;
3734 }
3735 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3736 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3737 S += '@';
3738 return;
3739 }
3740 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003741 }
Anders Carlssond8499822007-10-29 05:01:08 +00003742 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003743 getLegacyIntegralTypeEncoding(PointeeTy);
3744
Mike Stump11289f42009-09-09 15:08:12 +00003745 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003746 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003747 return;
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
Chris Lattnere7cabb92009-07-13 00:10:46 +00003750 if (const ArrayType *AT =
3751 // Ignore type qualifiers etc.
3752 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003753 if (isa<IncompleteArrayType>(AT)) {
3754 // Incomplete arrays are encoded as a pointer to the array element.
3755 S += '^';
3756
Mike Stump11289f42009-09-09 15:08:12 +00003757 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003758 false, ExpandStructures, FD);
3759 } else {
3760 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003761
Anders Carlssond05f44b2009-02-22 01:38:57 +00003762 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3763 S += llvm::utostr(CAT->getSize().getZExtValue());
3764 else {
3765 //Variable length arrays are encoded as a regular array with 0 elements.
3766 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3767 S += '0';
3768 }
Mike Stump11289f42009-09-09 15:08:12 +00003769
3770 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003771 false, ExpandStructures, FD);
3772 S += ']';
3773 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003774 return;
3775 }
Mike Stump11289f42009-09-09 15:08:12 +00003776
John McCall9dd450b2009-09-21 23:43:11 +00003777 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003778 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003779 return;
3780 }
Mike Stump11289f42009-09-09 15:08:12 +00003781
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003782 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003783 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003784 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003785 // Anonymous structures print as '?'
3786 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3787 S += II->getName();
3788 } else {
3789 S += '?';
3790 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003791 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003792 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003793 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3794 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003795 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003796 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003797 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003798 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003799 S += '"';
3800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003802 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003803 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003804 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003805 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003806 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003807 QualType qt = Field->getType();
3808 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003809 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003810 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003811 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003812 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003813 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003814 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003815 return;
3816 }
Mike Stump11289f42009-09-09 15:08:12 +00003817
Chris Lattnere7cabb92009-07-13 00:10:46 +00003818 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003819 if (FD && FD->isBitField())
3820 EncodeBitField(this, S, FD);
3821 else
3822 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003823 return;
3824 }
Mike Stump11289f42009-09-09 15:08:12 +00003825
Chris Lattnere7cabb92009-07-13 00:10:46 +00003826 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003827 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003828 return;
3829 }
Mike Stump11289f42009-09-09 15:08:12 +00003830
John McCall8ccfcb52009-09-24 19:53:00 +00003831 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003832 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003833 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003834 S += '{';
3835 const IdentifierInfo *II = OI->getIdentifier();
3836 S += II->getName();
3837 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003838 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003839 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003840 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003841 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003842 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003843 RecFields[i]);
3844 else
Mike Stump11289f42009-09-09 15:08:12 +00003845 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003846 FD);
3847 }
3848 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003849 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003850 }
Mike Stump11289f42009-09-09 15:08:12 +00003851
John McCall9dd450b2009-09-21 23:43:11 +00003852 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003853 if (OPT->isObjCIdType()) {
3854 S += '@';
3855 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003856 }
Mike Stump11289f42009-09-09 15:08:12 +00003857
Steve Narofff0c86112009-10-28 22:03:49 +00003858 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3859 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3860 // Since this is a binary compatibility issue, need to consult with runtime
3861 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003862 S += '#';
3863 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003864 }
Mike Stump11289f42009-09-09 15:08:12 +00003865
Chris Lattnere7cabb92009-07-13 00:10:46 +00003866 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003867 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003868 ExpandPointedToStructures,
3869 ExpandStructures, FD);
3870 if (FD || EncodingProperty) {
3871 // Note that we do extended encoding of protocol qualifer list
3872 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003873 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003874 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3875 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003876 S += '<';
3877 S += (*I)->getNameAsString();
3878 S += '>';
3879 }
3880 S += '"';
3881 }
3882 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003883 }
Mike Stump11289f42009-09-09 15:08:12 +00003884
Chris Lattnere7cabb92009-07-13 00:10:46 +00003885 QualType PointeeTy = OPT->getPointeeType();
3886 if (!EncodingProperty &&
3887 isa<TypedefType>(PointeeTy.getTypePtr())) {
3888 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003889 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003890 // {...};
3891 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003892 getObjCEncodingForTypeImpl(PointeeTy, S,
3893 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003894 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003895 return;
3896 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003897
3898 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003899 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003900 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003901 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003902 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3903 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003904 S += '<';
3905 S += (*I)->getNameAsString();
3906 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003907 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003908 S += '"';
3909 }
3910 return;
3911 }
Mike Stump11289f42009-09-09 15:08:12 +00003912
Chris Lattnere7cabb92009-07-13 00:10:46 +00003913 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003914}
3915
Mike Stump11289f42009-09-09 15:08:12 +00003916void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003917 std::string& S) const {
3918 if (QT & Decl::OBJC_TQ_In)
3919 S += 'n';
3920 if (QT & Decl::OBJC_TQ_Inout)
3921 S += 'N';
3922 if (QT & Decl::OBJC_TQ_Out)
3923 S += 'o';
3924 if (QT & Decl::OBJC_TQ_Bycopy)
3925 S += 'O';
3926 if (QT & Decl::OBJC_TQ_Byref)
3927 S += 'R';
3928 if (QT & Decl::OBJC_TQ_Oneway)
3929 S += 'V';
3930}
3931
Chris Lattnere7cabb92009-07-13 00:10:46 +00003932void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003933 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003934
Anders Carlsson87c149b2007-10-11 01:00:40 +00003935 BuiltinVaListType = T;
3936}
3937
Chris Lattnere7cabb92009-07-13 00:10:46 +00003938void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003939 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003940}
3941
Chris Lattnere7cabb92009-07-13 00:10:46 +00003942void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003943 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003944}
3945
Chris Lattnere7cabb92009-07-13 00:10:46 +00003946void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003947 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003948}
3949
Chris Lattnere7cabb92009-07-13 00:10:46 +00003950void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003951 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003952}
3953
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003954void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003955 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003956 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003957
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003958 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003959}
3960
John McCalld28ae272009-12-02 08:04:21 +00003961/// \brief Retrieve the template name that corresponds to a non-empty
3962/// lookup.
John McCallad371252010-01-20 00:46:10 +00003963TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3964 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003965 unsigned size = End - Begin;
3966 assert(size > 1 && "set is not overloaded!");
3967
3968 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3969 size * sizeof(FunctionTemplateDecl*));
3970 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3971
3972 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003973 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003974 NamedDecl *D = *I;
3975 assert(isa<FunctionTemplateDecl>(D) ||
3976 (isa<UsingShadowDecl>(D) &&
3977 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3978 *Storage++ = D;
3979 }
3980
3981 return TemplateName(OT);
3982}
3983
Douglas Gregordc572a32009-03-30 22:58:21 +00003984/// \brief Retrieve the template name that represents a qualified
3985/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003986TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003987 bool TemplateKeyword,
3988 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003989 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003990 llvm::FoldingSetNodeID ID;
3991 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3992
3993 void *InsertPos = 0;
3994 QualifiedTemplateName *QTN =
3995 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3996 if (!QTN) {
3997 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3998 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3999 }
4000
4001 return TemplateName(QTN);
4002}
4003
4004/// \brief Retrieve the template name that represents a dependent
4005/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004006TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004007 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004008 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004009 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004010
4011 llvm::FoldingSetNodeID ID;
4012 DependentTemplateName::Profile(ID, NNS, Name);
4013
4014 void *InsertPos = 0;
4015 DependentTemplateName *QTN =
4016 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4017
4018 if (QTN)
4019 return TemplateName(QTN);
4020
4021 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4022 if (CanonNNS == NNS) {
4023 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4024 } else {
4025 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4026 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004027 DependentTemplateName *CheckQTN =
4028 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4029 assert(!CheckQTN && "Dependent type name canonicalization broken");
4030 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004031 }
4032
4033 DependentTemplateNames.InsertNode(QTN, InsertPos);
4034 return TemplateName(QTN);
4035}
4036
Douglas Gregor71395fa2009-11-04 00:56:37 +00004037/// \brief Retrieve the template name that represents a dependent
4038/// template name such as \c MetaFun::template operator+.
4039TemplateName
4040ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4041 OverloadedOperatorKind Operator) {
4042 assert((!NNS || NNS->isDependent()) &&
4043 "Nested name specifier must be dependent");
4044
4045 llvm::FoldingSetNodeID ID;
4046 DependentTemplateName::Profile(ID, NNS, Operator);
4047
4048 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004049 DependentTemplateName *QTN
4050 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004051
4052 if (QTN)
4053 return TemplateName(QTN);
4054
4055 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4056 if (CanonNNS == NNS) {
4057 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4058 } else {
4059 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4060 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004061
4062 DependentTemplateName *CheckQTN
4063 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4064 assert(!CheckQTN && "Dependent template name canonicalization broken");
4065 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004066 }
4067
4068 DependentTemplateNames.InsertNode(QTN, InsertPos);
4069 return TemplateName(QTN);
4070}
4071
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004072/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004073/// TargetInfo, produce the corresponding type. The unsigned @p Type
4074/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004075CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004076 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004077 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004078 case TargetInfo::SignedShort: return ShortTy;
4079 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4080 case TargetInfo::SignedInt: return IntTy;
4081 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4082 case TargetInfo::SignedLong: return LongTy;
4083 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4084 case TargetInfo::SignedLongLong: return LongLongTy;
4085 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4086 }
4087
4088 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004089 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004090}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004091
4092//===----------------------------------------------------------------------===//
4093// Type Predicates.
4094//===----------------------------------------------------------------------===//
4095
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004096/// isObjCNSObjectType - Return true if this is an NSObject object using
4097/// NSObject attribute on a c-style pointer type.
4098/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004099/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004100///
4101bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4102 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4103 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004104 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004105 return true;
4106 }
Mike Stump11289f42009-09-09 15:08:12 +00004107 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004108}
4109
Fariborz Jahanian96207692009-02-18 21:49:28 +00004110/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4111/// garbage collection attribute.
4112///
John McCall8ccfcb52009-09-24 19:53:00 +00004113Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4114 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004115 if (getLangOptions().ObjC1 &&
4116 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004117 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004118 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004119 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004120 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004121 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004122 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004123 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004124 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004125 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004126 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004127 // Non-pointers have none gc'able attribute regardless of the attribute
4128 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004129 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004130 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004131 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004132 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004133}
4134
Chris Lattner49af6a42008-04-07 06:51:04 +00004135//===----------------------------------------------------------------------===//
4136// Type Compatibility Testing
4137//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004138
Mike Stump11289f42009-09-09 15:08:12 +00004139/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004140/// compatible.
4141static bool areCompatVectorTypes(const VectorType *LHS,
4142 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004143 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004144 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004145 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004146}
4147
Steve Naroff8e6aee52009-07-23 01:01:38 +00004148//===----------------------------------------------------------------------===//
4149// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4150//===----------------------------------------------------------------------===//
4151
4152/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4153/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004154bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4155 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004156 if (lProto == rProto)
4157 return true;
4158 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4159 E = rProto->protocol_end(); PI != E; ++PI)
4160 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4161 return true;
4162 return false;
4163}
4164
Steve Naroff8e6aee52009-07-23 01:01:38 +00004165/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4166/// return true if lhs's protocols conform to rhs's protocol; false
4167/// otherwise.
4168bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4169 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4170 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4171 return false;
4172}
4173
4174/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4175/// ObjCQualifiedIDType.
4176bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4177 bool compare) {
4178 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004179 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004180 lhs->isObjCIdType() || lhs->isObjCClassType())
4181 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004182 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004183 rhs->isObjCIdType() || rhs->isObjCClassType())
4184 return true;
4185
4186 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004187 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004188
Steve Naroff8e6aee52009-07-23 01:01:38 +00004189 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004190
Steve Naroff8e6aee52009-07-23 01:01:38 +00004191 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004192 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004193 // make sure we check the class hierarchy.
4194 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4195 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4196 E = lhsQID->qual_end(); I != E; ++I) {
4197 // when comparing an id<P> on lhs with a static type on rhs,
4198 // see if static class implements all of id's protocols, directly or
4199 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004200 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004201 return false;
4202 }
4203 }
4204 // If there are no qualifiers and no interface, we have an 'id'.
4205 return true;
4206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004208 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4209 E = lhsQID->qual_end(); I != E; ++I) {
4210 ObjCProtocolDecl *lhsProto = *I;
4211 bool match = false;
4212
4213 // when comparing an id<P> on lhs with a static type on rhs,
4214 // see if static class implements all of id's protocols, directly or
4215 // through its super class and categories.
4216 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4217 E = rhsOPT->qual_end(); J != E; ++J) {
4218 ObjCProtocolDecl *rhsProto = *J;
4219 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4220 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4221 match = true;
4222 break;
4223 }
4224 }
Mike Stump11289f42009-09-09 15:08:12 +00004225 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004226 // make sure we check the class hierarchy.
4227 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4228 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4229 E = lhsQID->qual_end(); I != E; ++I) {
4230 // when comparing an id<P> on lhs with a static type on rhs,
4231 // see if static class implements all of id's protocols, directly or
4232 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004233 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004234 match = true;
4235 break;
4236 }
4237 }
4238 }
4239 if (!match)
4240 return false;
4241 }
Mike Stump11289f42009-09-09 15:08:12 +00004242
Steve Naroff8e6aee52009-07-23 01:01:38 +00004243 return true;
4244 }
Mike Stump11289f42009-09-09 15:08:12 +00004245
Steve Naroff8e6aee52009-07-23 01:01:38 +00004246 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4247 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4248
Mike Stump11289f42009-09-09 15:08:12 +00004249 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004250 lhs->getAsObjCInterfacePointerType()) {
4251 if (lhsOPT->qual_empty()) {
4252 bool match = false;
4253 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4254 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4255 E = rhsQID->qual_end(); I != E; ++I) {
4256 // when comparing an id<P> on lhs with a static type on rhs,
4257 // see if static class implements all of id's protocols, directly or
4258 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004259 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004260 match = true;
4261 break;
4262 }
4263 }
4264 if (!match)
4265 return false;
4266 }
4267 return true;
4268 }
Mike Stump11289f42009-09-09 15:08:12 +00004269 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004270 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4271 E = lhsOPT->qual_end(); I != E; ++I) {
4272 ObjCProtocolDecl *lhsProto = *I;
4273 bool match = false;
4274
4275 // when comparing an id<P> on lhs with a static type on rhs,
4276 // see if static class implements all of id's protocols, directly or
4277 // through its super class and categories.
4278 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4279 E = rhsQID->qual_end(); J != E; ++J) {
4280 ObjCProtocolDecl *rhsProto = *J;
4281 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4282 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4283 match = true;
4284 break;
4285 }
4286 }
4287 if (!match)
4288 return false;
4289 }
4290 return true;
4291 }
4292 return false;
4293}
4294
Eli Friedman47f77112008-08-22 00:56:42 +00004295/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004296/// compatible for assignment from RHS to LHS. This handles validation of any
4297/// protocol qualifiers on the LHS or RHS.
4298///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004299bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4300 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004301 // If either type represents the built-in 'id' or 'Class' types, return true.
4302 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004303 return true;
4304
Steve Naroff8e6aee52009-07-23 01:01:38 +00004305 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00004306 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4307 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004308 false);
4309
Steve Naroff7cae42b2009-07-10 23:34:53 +00004310 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4311 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff8e6aee52009-07-23 01:01:38 +00004312 if (LHS && RHS) // We have 2 user-defined types.
4313 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004314
Steve Naroff8e6aee52009-07-23 01:01:38 +00004315 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004316}
4317
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004318/// getIntersectionOfProtocols - This routine finds the intersection of set
4319/// of protocols inherited from two distinct objective-c pointer objects.
4320/// It is used to build composite qualifier list of the composite type of
4321/// the conditional expression involving two objective-c pointer objects.
4322static
4323void getIntersectionOfProtocols(ASTContext &Context,
4324 const ObjCObjectPointerType *LHSOPT,
4325 const ObjCObjectPointerType *RHSOPT,
4326 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4327
4328 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4329 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4330
4331 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4332 unsigned LHSNumProtocols = LHS->getNumProtocols();
4333 if (LHSNumProtocols > 0)
4334 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4335 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004336 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4337 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004338 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4339 LHSInheritedProtocols.end());
4340 }
4341
4342 unsigned RHSNumProtocols = RHS->getNumProtocols();
4343 if (RHSNumProtocols > 0) {
4344 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4345 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4346 if (InheritedProtocolSet.count(RHSProtocols[i]))
4347 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4348 }
4349 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004350 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004351 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004352 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4353 RHSInheritedProtocols.begin(),
4354 E = RHSInheritedProtocols.end(); I != E; ++I)
4355 if (InheritedProtocolSet.count((*I)))
4356 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004357 }
4358}
4359
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004360/// areCommonBaseCompatible - Returns common base class of the two classes if
4361/// one found. Note that this is O'2 algorithm. But it will be called as the
4362/// last type comparison in a ?-exp of ObjC pointer types before a
4363/// warning is issued. So, its invokation is extremely rare.
4364QualType ASTContext::areCommonBaseCompatible(
4365 const ObjCObjectPointerType *LHSOPT,
4366 const ObjCObjectPointerType *RHSOPT) {
4367 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4368 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4369 if (!LHS || !RHS)
4370 return QualType();
4371
4372 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4373 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4374 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004375 if (canAssignObjCInterfaces(LHS, RHS)) {
4376 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4377 getIntersectionOfProtocols(*this,
4378 LHSOPT, RHSOPT, IntersectionOfProtocols);
4379 if (IntersectionOfProtocols.empty())
4380 LHSTy = getObjCObjectPointerType(LHSTy);
4381 else
4382 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4383 IntersectionOfProtocols.size());
4384 return LHSTy;
4385 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004386 }
4387
4388 return QualType();
4389}
4390
Eli Friedman47f77112008-08-22 00:56:42 +00004391bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4392 const ObjCInterfaceType *RHS) {
Chris Lattner49af6a42008-04-07 06:51:04 +00004393 // Verify that the base decls are compatible: the RHS must be a subclass of
4394 // the LHS.
4395 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4396 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004397
Chris Lattner49af6a42008-04-07 06:51:04 +00004398 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4399 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004400 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004401 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004402
Chris Lattner49af6a42008-04-07 06:51:04 +00004403 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4404 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004405 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004406 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004407
Steve Naroffc277ad12009-07-18 15:33:26 +00004408 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4409 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004410 LHSPI != LHSPE; LHSPI++) {
4411 bool RHSImplementsProtocol = false;
4412
4413 // If the RHS doesn't implement the protocol on the left, the types
4414 // are incompatible.
Steve Naroffc277ad12009-07-18 15:33:26 +00004415 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004416 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004417 RHSPI != RHSPE; RHSPI++) {
4418 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004419 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004420 break;
4421 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004422 }
4423 // FIXME: For better diagnostics, consider passing back the protocol name.
4424 if (!RHSImplementsProtocol)
4425 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004426 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004427 // The RHS implements all protocols listed on the LHS.
4428 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004429}
4430
Steve Naroffb7605152009-02-12 17:52:19 +00004431bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4432 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004433 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4434 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004435
Steve Naroff7cae42b2009-07-10 23:34:53 +00004436 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004437 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004438
4439 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4440 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004441}
4442
Mike Stump11289f42009-09-09 15:08:12 +00004443/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004444/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004445/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004446/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004447bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004448 if (getLangOptions().CPlusPlus)
4449 return hasSameType(LHS, RHS);
4450
Eli Friedman47f77112008-08-22 00:56:42 +00004451 return !mergeTypes(LHS, RHS).isNull();
4452}
4453
4454QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall9dd450b2009-09-21 23:43:11 +00004455 const FunctionType *lbase = lhs->getAs<FunctionType>();
4456 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004457 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4458 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004459 bool allLTypes = true;
4460 bool allRTypes = true;
4461
4462 // Check return type
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004463 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004464 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004465 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004466 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004467 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004468 allRTypes = false;
Mike Stumpea086c72009-07-25 23:24:03 +00004469 // FIXME: double check this
Mike Stump8c5d7992009-07-25 21:26:53 +00004470 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4471 if (NoReturn != lbase->getNoReturnAttr())
4472 allLTypes = false;
4473 if (NoReturn != rbase->getNoReturnAttr())
4474 allRTypes = false;
Douglas Gregor8c940862010-01-18 17:14:39 +00004475 CallingConv lcc = lbase->getCallConv();
4476 CallingConv rcc = rbase->getCallConv();
4477 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004478 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004479 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004480
Eli Friedman47f77112008-08-22 00:56:42 +00004481 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004482 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4483 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004484 unsigned lproto_nargs = lproto->getNumArgs();
4485 unsigned rproto_nargs = rproto->getNumArgs();
4486
4487 // Compatible functions must have the same number of arguments
4488 if (lproto_nargs != rproto_nargs)
4489 return QualType();
4490
4491 // Variadic and non-variadic functions aren't compatible
4492 if (lproto->isVariadic() != rproto->isVariadic())
4493 return QualType();
4494
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004495 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4496 return QualType();
4497
Eli Friedman47f77112008-08-22 00:56:42 +00004498 // Check argument compatibility
4499 llvm::SmallVector<QualType, 10> types;
4500 for (unsigned i = 0; i < lproto_nargs; i++) {
4501 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4502 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4503 QualType argtype = mergeTypes(largtype, rargtype);
4504 if (argtype.isNull()) return QualType();
4505 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004506 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4507 allLTypes = false;
4508 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4509 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004510 }
4511 if (allLTypes) return lhs;
4512 if (allRTypes) return rhs;
4513 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004514 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor8870a492010-02-12 17:17:28 +00004515 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004516 }
4517
4518 if (lproto) allRTypes = false;
4519 if (rproto) allLTypes = false;
4520
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004521 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004522 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004523 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004524 if (proto->isVariadic()) return QualType();
4525 // Check that the types are compatible with the types that
4526 // would result from default argument promotions (C99 6.7.5.3p15).
4527 // The only types actually affected are promotable integer
4528 // types and floats, which would be passed as a different
4529 // type depending on whether the prototype is visible.
4530 unsigned proto_nargs = proto->getNumArgs();
4531 for (unsigned i = 0; i < proto_nargs; ++i) {
4532 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004533
4534 // Look at the promotion type of enum types, since that is the type used
4535 // to pass enum values.
4536 if (const EnumType *Enum = argTy->getAs<EnumType>())
4537 argTy = Enum->getDecl()->getPromotionType();
4538
Eli Friedman47f77112008-08-22 00:56:42 +00004539 if (argTy->isPromotableIntegerType() ||
4540 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4541 return QualType();
4542 }
4543
4544 if (allLTypes) return lhs;
4545 if (allRTypes) return rhs;
4546 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004547 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004548 proto->getTypeQuals(),
4549 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004550 }
4551
4552 if (allLTypes) return lhs;
4553 if (allRTypes) return rhs;
Douglas Gregor8c940862010-01-18 17:14:39 +00004554 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004555}
4556
4557QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004558 // C++ [expr]: If an expression initially has the type "reference to T", the
4559 // type is adjusted to "T" prior to any further analysis, the expression
4560 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004561 // expression is an lvalue unless the reference is an rvalue reference and
4562 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004563 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4564 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4565
Eli Friedman47f77112008-08-22 00:56:42 +00004566 QualType LHSCan = getCanonicalType(LHS),
4567 RHSCan = getCanonicalType(RHS);
4568
4569 // If two types are identical, they are compatible.
4570 if (LHSCan == RHSCan)
4571 return LHS;
4572
John McCall8ccfcb52009-09-24 19:53:00 +00004573 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004574 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4575 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004576 if (LQuals != RQuals) {
4577 // If any of these qualifiers are different, we have a type
4578 // mismatch.
4579 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4580 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4581 return QualType();
4582
4583 // Exactly one GC qualifier difference is allowed: __strong is
4584 // okay if the other type has no GC qualifier but is an Objective
4585 // C object pointer (i.e. implicitly strong by default). We fix
4586 // this by pretending that the unqualified type was actually
4587 // qualified __strong.
4588 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4589 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4590 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4591
4592 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4593 return QualType();
4594
4595 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4596 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4597 }
4598 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4599 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4600 }
Eli Friedman47f77112008-08-22 00:56:42 +00004601 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004602 }
4603
4604 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004605
Eli Friedmandcca6332009-06-01 01:22:52 +00004606 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4607 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004608
Chris Lattnerfd652912008-01-14 05:45:46 +00004609 // We want to consider the two function types to be the same for these
4610 // comparisons, just force one to the other.
4611 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4612 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004613
4614 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004615 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4616 LHSClass = Type::ConstantArray;
4617 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4618 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004619
Nate Begemance4d7fc2008-04-18 23:10:10 +00004620 // Canonicalize ExtVector -> Vector.
4621 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4622 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004623
Chris Lattner95554662008-04-07 05:43:21 +00004624 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004625 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004626 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004627 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004628 // Compatibility is based on the underlying type, not the promotion
4629 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004630 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004631 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4632 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004633 }
John McCall9dd450b2009-09-21 23:43:11 +00004634 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004635 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4636 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004637 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004638
Eli Friedman47f77112008-08-22 00:56:42 +00004639 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004640 }
Eli Friedman47f77112008-08-22 00:56:42 +00004641
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004642 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004643 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004644#define TYPE(Class, Base)
4645#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004646#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004647#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4648#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4649#include "clang/AST/TypeNodes.def"
4650 assert(false && "Non-canonical and dependent types shouldn't get here");
4651 return QualType();
4652
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004653 case Type::LValueReference:
4654 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004655 case Type::MemberPointer:
4656 assert(false && "C++ should never be in mergeTypes");
4657 return QualType();
4658
4659 case Type::IncompleteArray:
4660 case Type::VariableArray:
4661 case Type::FunctionProto:
4662 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004663 assert(false && "Types are eliminated above");
4664 return QualType();
4665
Chris Lattnerfd652912008-01-14 05:45:46 +00004666 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004667 {
4668 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004669 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4670 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004671 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4672 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004673 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004674 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004675 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004676 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004677 return getPointerType(ResultType);
4678 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004679 case Type::BlockPointer:
4680 {
4681 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004682 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4683 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroff68e167d2008-12-10 17:49:55 +00004684 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4685 if (ResultType.isNull()) return QualType();
4686 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4687 return LHS;
4688 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4689 return RHS;
4690 return getBlockPointerType(ResultType);
4691 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004692 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004693 {
4694 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4695 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4696 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4697 return QualType();
4698
4699 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4700 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4701 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4702 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004703 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4704 return LHS;
4705 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4706 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004707 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4708 ArrayType::ArraySizeModifier(), 0);
4709 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4710 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004711 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4712 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004713 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4714 return LHS;
4715 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4716 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004717 if (LVAT) {
4718 // FIXME: This isn't correct! But tricky to implement because
4719 // the array's size has to be the size of LHS, but the type
4720 // has to be different.
4721 return LHS;
4722 }
4723 if (RVAT) {
4724 // FIXME: This isn't correct! But tricky to implement because
4725 // the array's size has to be the size of RHS, but the type
4726 // has to be different.
4727 return RHS;
4728 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004729 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4730 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004731 return getIncompleteArrayType(ResultType,
4732 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004733 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004734 case Type::FunctionNoProto:
Eli Friedman47f77112008-08-22 00:56:42 +00004735 return mergeFunctionTypes(LHS, RHS);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004736 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004737 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004738 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004739 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004740 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004741 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004742 case Type::Complex:
4743 // Distinct complex types are incompatible.
4744 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004745 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004746 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004747 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4748 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004749 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004750 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004751 case Type::ObjCInterface: {
Steve Naroff7a7814c2009-02-21 16:18:07 +00004752 // Check if the interfaces are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004753 // FIXME: This should be type compatibility, e.g. whether
4754 // "LHS x; RHS x;" at global scope is legal.
John McCall9dd450b2009-09-21 23:43:11 +00004755 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4756 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff7a7814c2009-02-21 16:18:07 +00004757 if (LHSIface && RHSIface &&
4758 canAssignObjCInterfaces(LHSIface, RHSIface))
4759 return LHS;
4760
Eli Friedman47f77112008-08-22 00:56:42 +00004761 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004762 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004763 case Type::ObjCObjectPointer: {
John McCall9dd450b2009-09-21 23:43:11 +00004764 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4765 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004766 return LHS;
4767
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004768 return QualType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004769 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004770 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004771
4772 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004773}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004774
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004775//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004776// Integer Predicates
4777//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004778
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004779unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004780 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004781 return 1;
John McCall56774992009-12-09 09:09:27 +00004782 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004783 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004784 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004785 return (unsigned)getTypeSize(T);
4786}
4787
4788QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4789 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004790
4791 // Turn <4 x signed int> -> <4 x unsigned int>
4792 if (const VectorType *VTy = T->getAs<VectorType>())
4793 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004794 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004795
4796 // For enums, we return the unsigned version of the base type.
4797 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004798 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004799
4800 const BuiltinType *BTy = T->getAs<BuiltinType>();
4801 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004802 switch (BTy->getKind()) {
4803 case BuiltinType::Char_S:
4804 case BuiltinType::SChar:
4805 return UnsignedCharTy;
4806 case BuiltinType::Short:
4807 return UnsignedShortTy;
4808 case BuiltinType::Int:
4809 return UnsignedIntTy;
4810 case BuiltinType::Long:
4811 return UnsignedLongTy;
4812 case BuiltinType::LongLong:
4813 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004814 case BuiltinType::Int128:
4815 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004816 default:
4817 assert(0 && "Unexpected signed integer type");
4818 return QualType();
4819 }
4820}
4821
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004822ExternalASTSource::~ExternalASTSource() { }
4823
4824void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004825
4826
4827//===----------------------------------------------------------------------===//
4828// Builtin Type Computation
4829//===----------------------------------------------------------------------===//
4830
4831/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4832/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004833static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004834 ASTContext::GetBuiltinTypeError &Error,
4835 bool AllowTypeModifiers = true) {
4836 // Modifiers.
4837 int HowLong = 0;
4838 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004839
Chris Lattnerecd79c62009-06-14 00:45:47 +00004840 // Read the modifiers first.
4841 bool Done = false;
4842 while (!Done) {
4843 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004844 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004845 case 'S':
4846 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4847 assert(!Signed && "Can't use 'S' modifier multiple times!");
4848 Signed = true;
4849 break;
4850 case 'U':
4851 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4852 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4853 Unsigned = true;
4854 break;
4855 case 'L':
4856 assert(HowLong <= 2 && "Can't have LLLL modifier");
4857 ++HowLong;
4858 break;
4859 }
4860 }
4861
4862 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004863
Chris Lattnerecd79c62009-06-14 00:45:47 +00004864 // Read the base type.
4865 switch (*Str++) {
4866 default: assert(0 && "Unknown builtin type letter!");
4867 case 'v':
4868 assert(HowLong == 0 && !Signed && !Unsigned &&
4869 "Bad modifiers used with 'v'!");
4870 Type = Context.VoidTy;
4871 break;
4872 case 'f':
4873 assert(HowLong == 0 && !Signed && !Unsigned &&
4874 "Bad modifiers used with 'f'!");
4875 Type = Context.FloatTy;
4876 break;
4877 case 'd':
4878 assert(HowLong < 2 && !Signed && !Unsigned &&
4879 "Bad modifiers used with 'd'!");
4880 if (HowLong)
4881 Type = Context.LongDoubleTy;
4882 else
4883 Type = Context.DoubleTy;
4884 break;
4885 case 's':
4886 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4887 if (Unsigned)
4888 Type = Context.UnsignedShortTy;
4889 else
4890 Type = Context.ShortTy;
4891 break;
4892 case 'i':
4893 if (HowLong == 3)
4894 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4895 else if (HowLong == 2)
4896 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4897 else if (HowLong == 1)
4898 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4899 else
4900 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4901 break;
4902 case 'c':
4903 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4904 if (Signed)
4905 Type = Context.SignedCharTy;
4906 else if (Unsigned)
4907 Type = Context.UnsignedCharTy;
4908 else
4909 Type = Context.CharTy;
4910 break;
4911 case 'b': // boolean
4912 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4913 Type = Context.BoolTy;
4914 break;
4915 case 'z': // size_t.
4916 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4917 Type = Context.getSizeType();
4918 break;
4919 case 'F':
4920 Type = Context.getCFConstantStringType();
4921 break;
4922 case 'a':
4923 Type = Context.getBuiltinVaListType();
4924 assert(!Type.isNull() && "builtin va list type not initialized!");
4925 break;
4926 case 'A':
4927 // This is a "reference" to a va_list; however, what exactly
4928 // this means depends on how va_list is defined. There are two
4929 // different kinds of va_list: ones passed by value, and ones
4930 // passed by reference. An example of a by-value va_list is
4931 // x86, where va_list is a char*. An example of by-ref va_list
4932 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4933 // we want this argument to be a char*&; for x86-64, we want
4934 // it to be a __va_list_tag*.
4935 Type = Context.getBuiltinVaListType();
4936 assert(!Type.isNull() && "builtin va list type not initialized!");
4937 if (Type->isArrayType()) {
4938 Type = Context.getArrayDecayedType(Type);
4939 } else {
4940 Type = Context.getLValueReferenceType(Type);
4941 }
4942 break;
4943 case 'V': {
4944 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004945 unsigned NumElements = strtoul(Str, &End, 10);
4946 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004947
Chris Lattnerecd79c62009-06-14 00:45:47 +00004948 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004949
Chris Lattnerecd79c62009-06-14 00:45:47 +00004950 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004951 // FIXME: Don't know what to do about AltiVec.
4952 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004953 break;
4954 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004955 case 'X': {
4956 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4957 Type = Context.getComplexType(ElementType);
4958 break;
4959 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004960 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004961 Type = Context.getFILEType();
4962 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004963 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004964 return QualType();
4965 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004966 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004967 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004968 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004969 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004970 else
4971 Type = Context.getjmp_bufType();
4972
Mike Stump2adb4da2009-07-28 23:47:15 +00004973 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004974 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004975 return QualType();
4976 }
4977 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004978 }
Mike Stump11289f42009-09-09 15:08:12 +00004979
Chris Lattnerecd79c62009-06-14 00:45:47 +00004980 if (!AllowTypeModifiers)
4981 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004982
Chris Lattnerecd79c62009-06-14 00:45:47 +00004983 Done = false;
4984 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004985 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004986 default: Done = true; --Str; break;
4987 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004988 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004989 {
4990 // Both pointers and references can have their pointee types
4991 // qualified with an address space.
4992 char *End;
4993 unsigned AddrSpace = strtoul(Str, &End, 10);
4994 if (End != Str && AddrSpace != 0) {
4995 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4996 Str = End;
4997 }
4998 }
4999 if (c == '*')
5000 Type = Context.getPointerType(Type);
5001 else
5002 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005003 break;
5004 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5005 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005006 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005007 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005008 case 'D':
5009 Type = Context.getVolatileType(Type);
5010 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005011 }
5012 }
Mike Stump11289f42009-09-09 15:08:12 +00005013
Chris Lattnerecd79c62009-06-14 00:45:47 +00005014 return Type;
5015}
5016
5017/// GetBuiltinType - Return the type for the specified builtin.
5018QualType ASTContext::GetBuiltinType(unsigned id,
5019 GetBuiltinTypeError &Error) {
5020 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005021
Chris Lattnerecd79c62009-06-14 00:45:47 +00005022 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005023
Chris Lattnerecd79c62009-06-14 00:45:47 +00005024 Error = GE_None;
5025 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5026 if (Error != GE_None)
5027 return QualType();
5028 while (TypeStr[0] && TypeStr[0] != '.') {
5029 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5030 if (Error != GE_None)
5031 return QualType();
5032
5033 // Do array -> pointer decay. The builtin should use the decayed type.
5034 if (Ty->isArrayType())
5035 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005036
Chris Lattnerecd79c62009-06-14 00:45:47 +00005037 ArgTypes.push_back(Ty);
5038 }
5039
5040 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5041 "'.' should only occur at end of builtin type list!");
5042
5043 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5044 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5045 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005046
5047 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005048 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005049 TypeStr[0] == '.', 0, false, false, 0, 0,
5050 false, CC_Default);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005051}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005052
5053QualType
5054ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5055 // Perform the usual unary conversions. We do this early so that
5056 // integral promotions to "int" can allow us to exit early, in the
5057 // lhs == rhs check. Also, for conversion purposes, we ignore any
5058 // qualifiers. For example, "const float" and "float" are
5059 // equivalent.
5060 if (lhs->isPromotableIntegerType())
5061 lhs = getPromotedIntegerType(lhs);
5062 else
5063 lhs = lhs.getUnqualifiedType();
5064 if (rhs->isPromotableIntegerType())
5065 rhs = getPromotedIntegerType(rhs);
5066 else
5067 rhs = rhs.getUnqualifiedType();
5068
5069 // If both types are identical, no conversion is needed.
5070 if (lhs == rhs)
5071 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005072
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005073 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5074 // The caller can deal with this (e.g. pointer + int).
5075 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5076 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005077
5078 // At this point, we have two different arithmetic types.
5079
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005080 // Handle complex types first (C99 6.3.1.8p1).
5081 if (lhs->isComplexType() || rhs->isComplexType()) {
5082 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005083 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005084 // convert the rhs to the lhs complex type.
5085 return lhs;
5086 }
Mike Stump11289f42009-09-09 15:08:12 +00005087 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005088 // convert the lhs to the rhs complex type.
5089 return rhs;
5090 }
5091 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005092 // When both operands are complex, the shorter operand is converted to the
5093 // type of the longer, and that is the type of the result. This corresponds
5094 // to what is done when combining two real floating-point operands.
5095 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005096 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005097 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005098 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005099 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005100 // "double _Complex" is promoted to "long double _Complex".
5101 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005102
5103 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005104 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005105 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005106 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005107 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005108 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5109 // domains match. This is a requirement for our implementation, C99
5110 // does not require this promotion.
5111 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5112 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5113 return rhs;
5114 } else { // handle "_Complex double, double".
5115 return lhs;
5116 }
5117 }
5118 return lhs; // The domain/size match exactly.
5119 }
5120 // Now handle "real" floating types (i.e. float, double, long double).
5121 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5122 // if we have an integer operand, the result is the real floating type.
5123 if (rhs->isIntegerType()) {
5124 // convert rhs to the lhs floating point type.
5125 return lhs;
5126 }
5127 if (rhs->isComplexIntegerType()) {
5128 // convert rhs to the complex floating point type.
5129 return getComplexType(lhs);
5130 }
5131 if (lhs->isIntegerType()) {
5132 // convert lhs to the rhs floating point type.
5133 return rhs;
5134 }
Mike Stump11289f42009-09-09 15:08:12 +00005135 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005136 // convert lhs to the complex floating point type.
5137 return getComplexType(rhs);
5138 }
5139 // We have two real floating types, float/complex combos were handled above.
5140 // Convert the smaller operand to the bigger result.
5141 int result = getFloatingTypeOrder(lhs, rhs);
5142 if (result > 0) // convert the rhs
5143 return lhs;
5144 assert(result < 0 && "illegal float comparison");
5145 return rhs; // convert the lhs
5146 }
5147 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5148 // Handle GCC complex int extension.
5149 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5150 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5151
5152 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005153 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005154 rhsComplexInt->getElementType()) >= 0)
5155 return lhs; // convert the rhs
5156 return rhs;
5157 } else if (lhsComplexInt && rhs->isIntegerType()) {
5158 // convert the rhs to the lhs complex type.
5159 return lhs;
5160 } else if (rhsComplexInt && lhs->isIntegerType()) {
5161 // convert the lhs to the rhs complex type.
5162 return rhs;
5163 }
5164 }
5165 // Finally, we have two differing integer types.
5166 // The rules for this case are in C99 6.3.1.8
5167 int compare = getIntegerTypeOrder(lhs, rhs);
5168 bool lhsSigned = lhs->isSignedIntegerType(),
5169 rhsSigned = rhs->isSignedIntegerType();
5170 QualType destType;
5171 if (lhsSigned == rhsSigned) {
5172 // Same signedness; use the higher-ranked type
5173 destType = compare >= 0 ? lhs : rhs;
5174 } else if (compare != (lhsSigned ? 1 : -1)) {
5175 // The unsigned type has greater than or equal rank to the
5176 // signed type, so use the unsigned type
5177 destType = lhsSigned ? rhs : lhs;
5178 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5179 // The two types are different widths; if we are here, that
5180 // means the signed type is larger than the unsigned type, so
5181 // use the signed type.
5182 destType = lhsSigned ? lhs : rhs;
5183 } else {
5184 // The signed type is higher-ranked than the unsigned type,
5185 // but isn't actually any bigger (like unsigned int and long
5186 // on most 32-bit systems). Use the unsigned type corresponding
5187 // to the signed type.
5188 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5189 }
5190 return destType;
5191}