blob: e2074e8b741a9f09b2d9146f7d2b447320b35fb9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +000044 NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000045 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000046 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +000047 NullTypeSourceInfo(QualType()),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +000048 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000049 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +000050 BuiltinInfo(builtins),
51 DeclarationNames(*this),
52 ExternalSource(0), PrintingPolicy(LOpts),
John McCall0c01d182010-03-24 05:22:00 +000053 LastSDM(0, 0) {
David Chisnall0f436562009-08-17 16:35:33 +000054 ObjCIdRedefinitionType = QualType();
55 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000056 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000057 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000058 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000059 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000060}
61
Reid Spencer5f016e22007-07-11 17:01:13 +000062ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +000063 // Release the DenseMaps associated with DeclContext objects.
64 // FIXME: Is this the ideal solution?
65 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +000066
Douglas Gregor00545312010-05-23 18:26:36 +000067 if (!FreeMemory) {
68 // Call all of the deallocation functions.
69 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
70 Deallocations[I].first(Deallocations[I].second);
71 }
72
Douglas Gregor7d10b7e2010-03-02 23:58:15 +000073 // Release all of the memory associated with overridden C++ methods.
74 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
75 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
76 OM != OMEnd; ++OM)
77 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +000078
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000079 if (FreeMemory) {
80 // Deallocate all the types.
81 while (!Types.empty()) {
82 Types.back()->Destroy(*this);
83 Types.pop_back();
84 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000085
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000086 for (llvm::FoldingSet<ExtQuals>::iterator
87 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
88 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000089 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000090 }
Nuno Lopesb74668e2008-12-17 22:30:25 +000091
Ted Kremenek503524a2010-03-08 20:56:29 +000092 for (llvm::DenseMap<const ObjCContainerDecl*,
93 const ASTRecordLayout*>::iterator
94 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
95 // Increment in loop to prevent using deallocated memory.
96 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
97 R->Destroy(*this);
98 }
Nuno Lopesb74668e2008-12-17 22:30:25 +000099 }
100
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000101 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
102 // even when using the BumpPtrAllocator because they can contain
103 // DenseMaps.
104 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
105 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
106 // Increment in loop to prevent using deallocated memory.
107 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
108 R->Destroy(*this);
109 }
110
Douglas Gregorab452ba2009-03-26 23:50:42 +0000111 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000112 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
113 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000114 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000115 NNS != NNSEnd; ) {
116 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000117 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000118 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000119
120 if (GlobalNestedNameSpecifier)
121 GlobalNestedNameSpecifier->Destroy(*this);
122
Eli Friedmanb26153c2008-05-27 03:08:09 +0000123 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000124}
125
Douglas Gregor00545312010-05-23 18:26:36 +0000126void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
127 Deallocations.push_back(std::make_pair(Callback, Data));
128}
129
Mike Stump1eb44332009-09-09 15:08:12 +0000130void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000131ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
132 ExternalSource.reset(Source.take());
133}
134
Reid Spencer5f016e22007-07-11 17:01:13 +0000135void ASTContext::PrintStats() const {
136 fprintf(stderr, "*** AST Context Stats:\n");
137 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000138
Douglas Gregordbe833d2009-05-26 14:40:08 +0000139 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000140#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000141#define ABSTRACT_TYPE(Name, Parent)
142#include "clang/AST/TypeNodes.def"
143 0 // Extra
144 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000145
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
147 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000148 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 }
150
Douglas Gregordbe833d2009-05-26 14:40:08 +0000151 unsigned Idx = 0;
152 unsigned TotalBytes = 0;
153#define TYPE(Name, Parent) \
154 if (counts[Idx]) \
155 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
156 TotalBytes += counts[Idx] * sizeof(Name##Type); \
157 ++Idx;
158#define ABSTRACT_TYPE(Name, Parent)
159#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Douglas Gregordbe833d2009-05-26 14:40:08 +0000161 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000162
163 if (ExternalSource.get()) {
164 fprintf(stderr, "\n");
165 ExternalSource->PrintStats();
166 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000167}
168
169
John McCalle27ec8a2009-10-23 23:03:21 +0000170void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000171 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000172 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000173 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174}
175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176void ASTContext::InitBuiltinTypes() {
177 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // C99 6.2.5p19.
180 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 // C99 6.2.5p2.
183 InitBuiltinType(BoolTy, BuiltinType::Bool);
184 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000185 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 InitBuiltinType(CharTy, BuiltinType::Char_S);
187 else
188 InitBuiltinType(CharTy, BuiltinType::Char_U);
189 // C99 6.2.5p4.
190 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
191 InitBuiltinType(ShortTy, BuiltinType::Short);
192 InitBuiltinType(IntTy, BuiltinType::Int);
193 InitBuiltinType(LongTy, BuiltinType::Long);
194 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 // C99 6.2.5p6.
197 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
198 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
199 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
200 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
201 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 // C99 6.2.5p10.
204 InitBuiltinType(FloatTy, BuiltinType::Float);
205 InitBuiltinType(DoubleTy, BuiltinType::Double);
206 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000207
Chris Lattner2df9ced2009-04-30 02:43:43 +0000208 // GNU extension, 128-bit integers.
209 InitBuiltinType(Int128Ty, BuiltinType::Int128);
210 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
211
Chris Lattner3a250322009-02-26 23:43:47 +0000212 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
213 InitBuiltinType(WCharTy, BuiltinType::WChar);
214 else // C99
215 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000216
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000217 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
218 InitBuiltinType(Char16Ty, BuiltinType::Char16);
219 else // C99
220 Char16Ty = getFromTargetType(Target.getChar16Type());
221
222 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
223 InitBuiltinType(Char32Ty, BuiltinType::Char32);
224 else // C99
225 Char32Ty = getFromTargetType(Target.getChar32Type());
226
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000228 InitBuiltinType(OverloadTy, BuiltinType::Overload);
229
230 // Placeholder type for type-dependent expressions whose type is
231 // completely unknown. No code should ever check a type against
232 // DependentTy and users should never see it; however, it is here to
233 // help diagnose failures to properly check for type-dependent
234 // expressions.
235 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236
Mike Stump1eb44332009-09-09 15:08:12 +0000237 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000238 // not yet been deduced.
239 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 // C99 6.2.5p11.
242 FloatComplexTy = getComplexType(FloatTy);
243 DoubleComplexTy = getComplexType(DoubleTy);
244 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000245
Steve Naroff7e219e42007-10-15 14:41:52 +0000246 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Steve Naroffde2e22d2009-07-15 18:40:39 +0000248 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
249 ObjCIdTypedefType = QualType();
250 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000251 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000253 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000254 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
255 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000256 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000257
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000260 // void * type
261 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000262
263 // nullptr type (C++0x 2.14.7)
264 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000265}
266
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000267MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000268ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000269 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000270 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000271 = InstantiatedFromStaticDataMember.find(Var);
272 if (Pos == InstantiatedFromStaticDataMember.end())
273 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Douglas Gregor7caa6822009-07-24 20:34:43 +0000275 return Pos->second;
276}
277
Mike Stump1eb44332009-09-09 15:08:12 +0000278void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000279ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
280 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000281 assert(Inst->isStaticDataMember() && "Not a static data member");
282 assert(Tmpl->isStaticDataMember() && "Not a static data member");
283 assert(!InstantiatedFromStaticDataMember[Inst] &&
284 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000285 InstantiatedFromStaticDataMember[Inst]
286 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000287}
288
John McCall7ba107a2009-11-18 02:36:19 +0000289NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000290ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000291 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000292 = InstantiatedFromUsingDecl.find(UUD);
293 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000294 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Anders Carlsson0d8df782009-08-29 19:37:28 +0000296 return Pos->second;
297}
298
299void
John McCalled976492009-12-04 22:46:56 +0000300ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
301 assert((isa<UsingDecl>(Pattern) ||
302 isa<UnresolvedUsingValueDecl>(Pattern) ||
303 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
304 "pattern decl is not a using decl");
305 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
306 InstantiatedFromUsingDecl[Inst] = Pattern;
307}
308
309UsingShadowDecl *
310ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
311 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
312 = InstantiatedFromUsingShadowDecl.find(Inst);
313 if (Pos == InstantiatedFromUsingShadowDecl.end())
314 return 0;
315
316 return Pos->second;
317}
318
319void
320ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
321 UsingShadowDecl *Pattern) {
322 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
323 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000324}
325
Anders Carlssond8b285f2009-09-01 04:26:58 +0000326FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
327 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
328 = InstantiatedFromUnnamedFieldDecl.find(Field);
329 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
330 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Anders Carlssond8b285f2009-09-01 04:26:58 +0000332 return Pos->second;
333}
334
335void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
336 FieldDecl *Tmpl) {
337 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
338 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
339 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
340 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Anders Carlssond8b285f2009-09-01 04:26:58 +0000342 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
343}
344
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000345ASTContext::overridden_cxx_method_iterator
346ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
347 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
348 = OverriddenMethods.find(Method);
349 if (Pos == OverriddenMethods.end())
350 return 0;
351
352 return Pos->second.begin();
353}
354
355ASTContext::overridden_cxx_method_iterator
356ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
357 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
358 = OverriddenMethods.find(Method);
359 if (Pos == OverriddenMethods.end())
360 return 0;
361
362 return Pos->second.end();
363}
364
365void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
366 const CXXMethodDecl *Overridden) {
367 OverriddenMethods[Method].push_back(Overridden);
368}
369
Douglas Gregor2e222532009-07-02 17:08:52 +0000370namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000371 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000372 : std::binary_function<SourceRange, SourceRange, bool> {
373 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor2e222532009-07-02 17:08:52 +0000375 public:
376 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Douglas Gregor2e222532009-07-02 17:08:52 +0000378 bool operator()(SourceRange X, SourceRange Y) {
379 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
380 }
381 };
382}
383
Chris Lattner464175b2007-07-18 17:52:12 +0000384//===----------------------------------------------------------------------===//
385// Type Sizing and Analysis
386//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000387
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000388/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
389/// scalar floating point type.
390const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000391 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000392 assert(BT && "Not a floating point type!");
393 switch (BT->getKind()) {
394 default: assert(0 && "Not a floating point type!");
395 case BuiltinType::Float: return Target.getFloatFormat();
396 case BuiltinType::Double: return Target.getDoubleFormat();
397 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
398 }
399}
400
Ken Dyck8b752f12010-01-27 17:10:57 +0000401/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000402/// specified decl. Note that bitfields do not have a valid alignment, so
403/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000404/// If @p RefAsPointee, references are treated like their underlying type
405/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000406CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000407 unsigned Align = Target.getCharWidth();
408
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000409 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000410 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000411
Chris Lattneraf707ab2009-01-24 21:53:27 +0000412 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
413 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000414 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000415 if (RefAsPointee)
416 T = RT->getPointeeType();
417 else
418 T = getPointerType(RT->getPointeeType());
419 }
420 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000421 unsigned MinWidth = Target.getLargeArrayMinWidth();
422 unsigned ArrayAlign = Target.getLargeArrayAlign();
423 if (isa<VariableArrayType>(T) && MinWidth != 0)
424 Align = std::max(Align, ArrayAlign);
425 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
426 unsigned Size = getTypeSize(CT);
427 if (MinWidth != 0 && MinWidth <= Size)
428 Align = std::max(Align, ArrayAlign);
429 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000430 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000431 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
432 T = cast<ArrayType>(T)->getElementType();
433
434 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
435 }
Charles Davis05f62472010-02-23 04:52:00 +0000436 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
437 // In the case of a field in a packed struct, we want the minimum
438 // of the alignment of the field and the alignment of the struct.
439 Align = std::min(Align,
440 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
441 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000442 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000443
Ken Dyck8b752f12010-01-27 17:10:57 +0000444 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000445}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000446
John McCallea1471e2010-05-20 01:18:31 +0000447std::pair<CharUnits, CharUnits>
448ASTContext::getTypeInfoInChars(const Type *T) {
449 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
450 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
451 CharUnits::fromQuantity(Info.second / getCharWidth()));
452}
453
454std::pair<CharUnits, CharUnits>
455ASTContext::getTypeInfoInChars(QualType T) {
456 return getTypeInfoInChars(T.getTypePtr());
457}
458
Chris Lattnera7674d82007-07-13 22:13:22 +0000459/// getTypeSize - Return the size of the specified type, in bits. This method
460/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000461///
462/// FIXME: Pointers into different addr spaces could have different sizes and
463/// alignment requirements: getPointerInfo should take an AddrSpace, this
464/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000465std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000466ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000467 uint64_t Width=0;
468 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000469 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000470#define TYPE(Class, Base)
471#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000472#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000473#define DEPENDENT_TYPE(Class, Base) case Type::Class:
474#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000475 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000476 break;
477
Chris Lattner692233e2007-07-13 22:27:08 +0000478 case Type::FunctionNoProto:
479 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000480 // GCC extension: alignof(function) = 32 bits
481 Width = 0;
482 Align = 32;
483 break;
484
Douglas Gregor72564e72009-02-26 23:50:07 +0000485 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000486 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000487 Width = 0;
488 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
489 break;
490
Steve Narofffb22d962007-08-30 01:06:46 +0000491 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000492 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattner98be4942008-03-05 18:54:05 +0000494 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000495 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000496 Align = EltInfo.second;
497 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000498 }
Nate Begeman213541a2008-04-18 23:10:10 +0000499 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000500 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000501 const VectorType *VT = cast<VectorType>(T);
502 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
503 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000504 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000505 // If the alignment is not a power of 2, round up to the next power of 2.
506 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000507 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000508 Align = llvm::NextPowerOf2(Align);
509 Width = llvm::RoundUpToAlignment(Width, Align);
510 }
Chris Lattner030d8842007-07-19 22:06:24 +0000511 break;
512 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000513
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000514 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000515 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000516 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000517 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000518 // GCC extension: alignof(void) = 8 bits.
519 Width = 0;
520 Align = 8;
521 break;
522
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000523 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000524 Width = Target.getBoolWidth();
525 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000526 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000527 case BuiltinType::Char_S:
528 case BuiltinType::Char_U:
529 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000530 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000531 Width = Target.getCharWidth();
532 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000533 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000534 case BuiltinType::WChar:
535 Width = Target.getWCharWidth();
536 Align = Target.getWCharAlign();
537 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000538 case BuiltinType::Char16:
539 Width = Target.getChar16Width();
540 Align = Target.getChar16Align();
541 break;
542 case BuiltinType::Char32:
543 Width = Target.getChar32Width();
544 Align = Target.getChar32Align();
545 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000546 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000547 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000548 Width = Target.getShortWidth();
549 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000550 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000551 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000552 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000553 Width = Target.getIntWidth();
554 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000555 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000556 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000557 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000558 Width = Target.getLongWidth();
559 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000560 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000561 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000562 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000563 Width = Target.getLongLongWidth();
564 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000565 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000566 case BuiltinType::Int128:
567 case BuiltinType::UInt128:
568 Width = 128;
569 Align = 128; // int128_t is 128-bit aligned on all targets.
570 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000571 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000572 Width = Target.getFloatWidth();
573 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000574 break;
575 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000576 Width = Target.getDoubleWidth();
577 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000578 break;
579 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000580 Width = Target.getLongDoubleWidth();
581 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000582 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000583 case BuiltinType::NullPtr:
584 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
585 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000586 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000587 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000588 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000589 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000590 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000591 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000592 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000593 case Type::BlockPointer: {
594 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
595 Width = Target.getPointerWidth(AS);
596 Align = Target.getPointerAlign(AS);
597 break;
598 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000599 case Type::LValueReference:
600 case Type::RValueReference: {
601 // alignof and sizeof should never enter this code path here, so we go
602 // the pointer route.
603 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
604 Width = Target.getPointerWidth(AS);
605 Align = Target.getPointerAlign(AS);
606 break;
607 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000608 case Type::Pointer: {
609 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000610 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000611 Align = Target.getPointerAlign(AS);
612 break;
613 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000614 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000615 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000616 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000617 getTypeInfo(getPointerDiffType());
618 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000619 if (Pointee->isFunctionType())
620 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000621 Align = PtrDiffInfo.second;
622 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000623 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000624 case Type::Complex: {
625 // Complex types have the same alignment as their elements, but twice the
626 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000627 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000628 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000629 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000630 Align = EltInfo.second;
631 break;
632 }
John McCallc12c5bb2010-05-15 11:32:37 +0000633 case Type::ObjCObject:
634 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000635 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000636 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000637 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
638 Width = Layout.getSize();
639 Align = Layout.getAlignment();
640 break;
641 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000642 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000643 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000644 const TagType *TT = cast<TagType>(T);
645
646 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000647 Width = 1;
648 Align = 1;
649 break;
650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Daniel Dunbar1d751182008-11-08 05:48:37 +0000652 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000653 return getTypeInfo(ET->getDecl()->getIntegerType());
654
Daniel Dunbar1d751182008-11-08 05:48:37 +0000655 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000656 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
657 Width = Layout.getSize();
658 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000659 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000660 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000661
Chris Lattner9fcfe922009-10-22 05:17:15 +0000662 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000663 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
664 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000665
Douglas Gregor18857642009-04-30 17:32:17 +0000666 case Type::Typedef: {
667 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000668 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000669 Align = std::max(Aligned->getMaxAlignment(),
670 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000671 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
672 } else
673 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000674 break;
Chris Lattner71763312008-04-06 22:05:18 +0000675 }
Douglas Gregor18857642009-04-30 17:32:17 +0000676
677 case Type::TypeOfExpr:
678 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
679 .getTypePtr());
680
681 case Type::TypeOf:
682 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
683
Anders Carlsson395b4752009-06-24 19:06:50 +0000684 case Type::Decltype:
685 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
686 .getTypePtr());
687
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000688 case Type::Elaborated:
689 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Douglas Gregor18857642009-04-30 17:32:17 +0000691 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000692 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000693 "Cannot request the size of a dependent type");
694 // FIXME: this is likely to be wrong once we support template
695 // aliases, since a template alias could refer to a typedef that
696 // has an __aligned__ attribute on it.
697 return getTypeInfo(getCanonicalType(T));
698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner464175b2007-07-18 17:52:12 +0000700 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000701 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000702}
703
Ken Dyckbdc601b2009-12-22 14:23:30 +0000704/// getTypeSizeInChars - Return the size of the specified type, in characters.
705/// This method does not work on incomplete types.
706CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000707 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000708}
709CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000710 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000711}
712
Ken Dyck16e20cc2010-01-26 17:25:18 +0000713/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000714/// characters. This method does not work on incomplete types.
715CharUnits ASTContext::getTypeAlignInChars(QualType T) {
716 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
717}
718CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
719 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
720}
721
Chris Lattner34ebde42009-01-27 18:08:34 +0000722/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
723/// type for the current target in bits. This can be different than the ABI
724/// alignment in cases where it is beneficial for performance to overalign
725/// a data type.
726unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
727 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000728
729 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000730 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000731 T = CT->getElementType().getTypePtr();
732 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
733 T->isSpecificBuiltinType(BuiltinType::LongLong))
734 return std::max(ABIAlign, (unsigned)getTypeSize(T));
735
Chris Lattner34ebde42009-01-27 18:08:34 +0000736 return ABIAlign;
737}
738
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000739static void CollectLocalObjCIvars(ASTContext *Ctx,
740 const ObjCInterfaceDecl *OI,
741 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000742 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
743 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000744 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000745 if (!IVDecl->isInvalidDecl())
746 Fields.push_back(cast<FieldDecl>(IVDecl));
747 }
748}
749
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000750void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
751 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
752 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
753 CollectObjCIvars(SuperClass, Fields);
754 CollectLocalObjCIvars(this, OI, Fields);
755}
756
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000757/// ShallowCollectObjCIvars -
758/// Collect all ivars, including those synthesized, in the current class.
759///
760void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000761 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000762 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
763 E = OI->ivar_end(); I != E; ++I) {
764 Ivars.push_back(*I);
765 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000766
767 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000768}
769
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000770/// CollectNonClassIvars -
771/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000772/// This includes synthesized ivars (via @synthesize) and those in
773// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000774///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000775void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000776 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000777 // Find ivars declared in class extension.
778 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
779 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
780 E = CDecl->ivar_end(); I != E; ++I) {
781 Ivars.push_back(*I);
782 }
783 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000784
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000785 // Also add any ivar defined in this class's implementation. This
786 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000787 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
788 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
789 E = ImplDecl->ivar_end(); I != E; ++I)
790 Ivars.push_back(*I);
791 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000792}
793
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000794/// CollectInheritedProtocols - Collect all protocols in current class and
795/// those inherited by it.
796void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000797 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000798 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
799 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
800 PE = OI->protocol_end(); P != PE; ++P) {
801 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000802 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000803 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000804 PE = Proto->protocol_end(); P != PE; ++P) {
805 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000806 CollectInheritedProtocols(*P, Protocols);
807 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000808 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000809
810 // Categories of this Interface.
811 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
812 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
813 CollectInheritedProtocols(CDeclChain, Protocols);
814 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
815 while (SD) {
816 CollectInheritedProtocols(SD, Protocols);
817 SD = SD->getSuperClass();
818 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000819 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000820 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
821 PE = OC->protocol_end(); P != PE; ++P) {
822 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000823 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000824 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
825 PE = Proto->protocol_end(); P != PE; ++P)
826 CollectInheritedProtocols(*P, Protocols);
827 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000828 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000829 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
830 PE = OP->protocol_end(); P != PE; ++P) {
831 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000832 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000833 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
834 PE = Proto->protocol_end(); P != PE; ++P)
835 CollectInheritedProtocols(*P, Protocols);
836 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000837 }
838}
839
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000840unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
841 unsigned count = 0;
842 // Count ivars declared in class extension.
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000843 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension())
844 count += CDecl->ivar_size();
845
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000846 // Count ivar defined in this class's implementation. This
847 // includes synthesized ivars.
848 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000849 count += ImplDecl->ivar_size();
850
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000851 return count;
852}
853
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000854/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
855ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
856 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
857 I = ObjCImpls.find(D);
858 if (I != ObjCImpls.end())
859 return cast<ObjCImplementationDecl>(I->second);
860 return 0;
861}
862/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
863ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
864 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
865 I = ObjCImpls.find(D);
866 if (I != ObjCImpls.end())
867 return cast<ObjCCategoryImplDecl>(I->second);
868 return 0;
869}
870
871/// \brief Set the implementation of ObjCInterfaceDecl.
872void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
873 ObjCImplementationDecl *ImplD) {
874 assert(IFaceD && ImplD && "Passed null params");
875 ObjCImpls[IFaceD] = ImplD;
876}
877/// \brief Set the implementation of ObjCCategoryDecl.
878void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
879 ObjCCategoryImplDecl *ImplD) {
880 assert(CatD && ImplD && "Passed null params");
881 ObjCImpls[CatD] = ImplD;
882}
883
John McCalla93c9342009-12-07 02:54:59 +0000884/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000885///
John McCalla93c9342009-12-07 02:54:59 +0000886/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000887/// the TypeLoc wrappers.
888///
889/// \param T the type that will be the basis for type source info. This type
890/// should refer to how the declarator was written in source code, not to
891/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000892TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000893 unsigned DataSize) {
894 if (!DataSize)
895 DataSize = TypeLoc::getFullDataSizeForType(T);
896 else
897 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +0000898 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +0000899
John McCalla93c9342009-12-07 02:54:59 +0000900 TypeSourceInfo *TInfo =
901 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
902 new (TInfo) TypeSourceInfo(T);
903 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000904}
905
John McCalla93c9342009-12-07 02:54:59 +0000906TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +0000907 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +0000908 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +0000909 DI->getTypeLoc().initialize(L);
910 return DI;
911}
912
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000913const ASTRecordLayout &
914ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
915 return getObjCLayout(D, 0);
916}
917
918const ASTRecordLayout &
919ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
920 return getObjCLayout(D->getClassInterface(), D);
921}
922
Chris Lattnera7674d82007-07-13 22:13:22 +0000923//===----------------------------------------------------------------------===//
924// Type creation/memoization methods
925//===----------------------------------------------------------------------===//
926
John McCall0953e762009-09-24 19:53:00 +0000927QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
928 unsigned Fast = Quals.getFastQualifiers();
929 Quals.removeFastQualifiers();
930
931 // Check if we've already instantiated this type.
932 llvm::FoldingSetNodeID ID;
933 ExtQuals::Profile(ID, TypeNode, Quals);
934 void *InsertPos = 0;
935 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
936 assert(EQ->getQualifiers() == Quals);
937 QualType T = QualType(EQ, Fast);
938 return T;
939 }
940
John McCall6b304a02009-09-24 23:30:46 +0000941 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +0000942 ExtQualNodes.InsertNode(New, InsertPos);
943 QualType T = QualType(New, Fast);
944 return T;
945}
946
947QualType ASTContext::getVolatileType(QualType T) {
948 QualType CanT = getCanonicalType(T);
949 if (CanT.isVolatileQualified()) return T;
950
951 QualifierCollector Quals;
952 const Type *TypeNode = Quals.strip(T);
953 Quals.addVolatile();
954
955 return getExtQualType(TypeNode, Quals);
956}
957
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000958QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000959 QualType CanT = getCanonicalType(T);
960 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000961 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000962
John McCall0953e762009-09-24 19:53:00 +0000963 // If we are composing extended qualifiers together, merge together
964 // into one ExtQuals node.
965 QualifierCollector Quals;
966 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
John McCall0953e762009-09-24 19:53:00 +0000968 // If this type already has an address space specified, it cannot get
969 // another one.
970 assert(!Quals.hasAddressSpace() &&
971 "Type cannot be in multiple addr spaces!");
972 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
John McCall0953e762009-09-24 19:53:00 +0000974 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000975}
976
Chris Lattnerb7d25532009-02-18 22:53:11 +0000977QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +0000978 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000979 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000980 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000981 return T;
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000983 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000984 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000985 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000986 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
987 return getPointerType(ResultType);
988 }
989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
John McCall0953e762009-09-24 19:53:00 +0000991 // If we are composing extended qualifiers together, merge together
992 // into one ExtQuals node.
993 QualifierCollector Quals;
994 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000995
John McCall0953e762009-09-24 19:53:00 +0000996 // If this type already has an ObjCGC specified, it cannot get
997 // another one.
998 assert(!Quals.hasObjCGCAttr() &&
999 "Type cannot have multiple ObjCGCs!");
1000 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
John McCall0953e762009-09-24 19:53:00 +00001002 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001003}
Chris Lattnera7674d82007-07-13 22:13:22 +00001004
Rafael Espindola264ba482010-03-30 20:24:48 +00001005static QualType getExtFunctionType(ASTContext& Context, QualType T,
1006 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001007 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001008 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1009 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001010 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001011 if (ResultType == Pointee)
1012 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001013
1014 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001015 } else if (const BlockPointerType *BlockPointer
1016 = T->getAs<BlockPointerType>()) {
1017 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001018 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001019 if (ResultType == Pointee)
1020 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001021
1022 ResultType = Context.getBlockPointerType(ResultType);
1023 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001024 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001025 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001026
Douglas Gregor43c79c22009-12-09 00:47:37 +00001027 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001028 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001029 Info);
John McCall0953e762009-09-24 19:53:00 +00001030 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001031 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001032 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001033 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1034 FPT->getNumArgs(), FPT->isVariadic(),
1035 FPT->getTypeQuals(),
1036 FPT->hasExceptionSpec(),
1037 FPT->hasAnyExceptionSpec(),
1038 FPT->getNumExceptions(),
1039 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001040 Info);
John McCall0953e762009-09-24 19:53:00 +00001041 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001042 } else
1043 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001044
1045 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1046}
1047
1048QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001049 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001050 return getExtFunctionType(*this, T,
1051 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001052}
1053
1054QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001055 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001056 return getExtFunctionType(*this, T,
1057 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001058}
1059
Rafael Espindola425ef722010-03-30 22:15:11 +00001060QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1061 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1062 return getExtFunctionType(*this, T,
1063 Info.withRegParm(RegParm));
1064}
1065
Reid Spencer5f016e22007-07-11 17:01:13 +00001066/// getComplexType - Return the uniqued reference to the type for a complex
1067/// number with the specified element type.
1068QualType ASTContext::getComplexType(QualType T) {
1069 // Unique pointers, to guarantee there is only one pointer of a particular
1070 // structure.
1071 llvm::FoldingSetNodeID ID;
1072 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 void *InsertPos = 0;
1075 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1076 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 // If the pointee type isn't canonical, this won't be a canonical type either,
1079 // so fill in the canonical type field.
1080 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001081 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001082 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 // Get the new insert position for the node we care about.
1085 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001086 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 }
John McCall6b304a02009-09-24 23:30:46 +00001088 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 Types.push_back(New);
1090 ComplexTypes.InsertNode(New, InsertPos);
1091 return QualType(New, 0);
1092}
1093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094/// getPointerType - Return the uniqued reference to the type for a pointer to
1095/// the specified type.
1096QualType ASTContext::getPointerType(QualType T) {
1097 // Unique pointers, to guarantee there is only one pointer of a particular
1098 // structure.
1099 llvm::FoldingSetNodeID ID;
1100 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 void *InsertPos = 0;
1103 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1104 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // If the pointee type isn't canonical, this won't be a canonical type either,
1107 // so fill in the canonical type field.
1108 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001109 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001110 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 // Get the new insert position for the node we care about.
1113 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001114 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 }
John McCall6b304a02009-09-24 23:30:46 +00001116 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 Types.push_back(New);
1118 PointerTypes.InsertNode(New, InsertPos);
1119 return QualType(New, 0);
1120}
1121
Mike Stump1eb44332009-09-09 15:08:12 +00001122/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001123/// a pointer to the specified block.
1124QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001125 assert(T->isFunctionType() && "block of function types only");
1126 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001127 // structure.
1128 llvm::FoldingSetNodeID ID;
1129 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Steve Naroff5618bd42008-08-27 16:04:49 +00001131 void *InsertPos = 0;
1132 if (BlockPointerType *PT =
1133 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1134 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
1136 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001137 // type either so fill in the canonical type field.
1138 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001139 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001140 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Steve Naroff5618bd42008-08-27 16:04:49 +00001142 // Get the new insert position for the node we care about.
1143 BlockPointerType *NewIP =
1144 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001145 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001146 }
John McCall6b304a02009-09-24 23:30:46 +00001147 BlockPointerType *New
1148 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001149 Types.push_back(New);
1150 BlockPointerTypes.InsertNode(New, InsertPos);
1151 return QualType(New, 0);
1152}
1153
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001154/// getLValueReferenceType - Return the uniqued reference to the type for an
1155/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001156QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 // Unique pointers, to guarantee there is only one pointer of a particular
1158 // structure.
1159 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001160 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161
1162 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001163 if (LValueReferenceType *RT =
1164 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001166
John McCall54e14c42009-10-22 22:37:11 +00001167 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1168
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 // If the referencee type isn't canonical, this won't be a canonical type
1170 // either, so fill in the canonical type field.
1171 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001172 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1173 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1174 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001175
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001177 LValueReferenceType *NewIP =
1178 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001179 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 }
1181
John McCall6b304a02009-09-24 23:30:46 +00001182 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001183 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1184 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001186 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001187
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001188 return QualType(New, 0);
1189}
1190
1191/// getRValueReferenceType - Return the uniqued reference to the type for an
1192/// rvalue reference to the specified type.
1193QualType ASTContext::getRValueReferenceType(QualType T) {
1194 // Unique pointers, to guarantee there is only one pointer of a particular
1195 // structure.
1196 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001197 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001198
1199 void *InsertPos = 0;
1200 if (RValueReferenceType *RT =
1201 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1202 return QualType(RT, 0);
1203
John McCall54e14c42009-10-22 22:37:11 +00001204 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1205
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001206 // If the referencee type isn't canonical, this won't be a canonical type
1207 // either, so fill in the canonical type field.
1208 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001209 if (InnerRef || !T.isCanonical()) {
1210 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1211 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001212
1213 // Get the new insert position for the node we care about.
1214 RValueReferenceType *NewIP =
1215 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1216 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1217 }
1218
John McCall6b304a02009-09-24 23:30:46 +00001219 RValueReferenceType *New
1220 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001221 Types.push_back(New);
1222 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 return QualType(New, 0);
1224}
1225
Sebastian Redlf30208a2009-01-24 21:16:55 +00001226/// getMemberPointerType - Return the uniqued reference to the type for a
1227/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001228QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001229 // Unique pointers, to guarantee there is only one pointer of a particular
1230 // structure.
1231 llvm::FoldingSetNodeID ID;
1232 MemberPointerType::Profile(ID, T, Cls);
1233
1234 void *InsertPos = 0;
1235 if (MemberPointerType *PT =
1236 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1237 return QualType(PT, 0);
1238
1239 // If the pointee or class type isn't canonical, this won't be a canonical
1240 // type either, so fill in the canonical type field.
1241 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001242 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001243 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1244
1245 // Get the new insert position for the node we care about.
1246 MemberPointerType *NewIP =
1247 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1248 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1249 }
John McCall6b304a02009-09-24 23:30:46 +00001250 MemberPointerType *New
1251 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001252 Types.push_back(New);
1253 MemberPointerTypes.InsertNode(New, InsertPos);
1254 return QualType(New, 0);
1255}
1256
Mike Stump1eb44332009-09-09 15:08:12 +00001257/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001258/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001259QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001260 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001261 ArrayType::ArraySizeModifier ASM,
1262 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001263 assert((EltTy->isDependentType() ||
1264 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001265 "Constant array of VLAs is illegal!");
1266
Chris Lattner38aeec72009-05-13 04:12:56 +00001267 // Convert the array size into a canonical width matching the pointer size for
1268 // the target.
1269 llvm::APInt ArySize(ArySizeIn);
1270 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001273 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001276 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001277 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 // If the element type isn't canonical, this won't be a canonical type either,
1281 // so fill in the canonical type field.
1282 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001283 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001284 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001285 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001287 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001288 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001289 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
John McCall6b304a02009-09-24 23:30:46 +00001292 ConstantArrayType *New = new(*this,TypeAlignment)
1293 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001294 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 Types.push_back(New);
1296 return QualType(New, 0);
1297}
1298
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001299/// getVariableArrayType - Returns a non-unique reference to the type for a
1300/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001301QualType ASTContext::getVariableArrayType(QualType EltTy,
1302 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001303 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001304 unsigned EltTypeQuals,
1305 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001306 // Since we don't unique expressions, it isn't possible to unique VLA's
1307 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001308 QualType CanonType;
1309
1310 if (!EltTy.isCanonical()) {
1311 if (NumElts)
1312 NumElts->Retain();
1313 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1314 EltTypeQuals, Brackets);
1315 }
1316
John McCall6b304a02009-09-24 23:30:46 +00001317 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001318 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001319
1320 VariableArrayTypes.push_back(New);
1321 Types.push_back(New);
1322 return QualType(New, 0);
1323}
1324
Douglas Gregor898574e2008-12-05 23:32:09 +00001325/// getDependentSizedArrayType - Returns a non-unique reference to
1326/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001327/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001328QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1329 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001330 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001331 unsigned EltTypeQuals,
1332 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001333 assert((!NumElts || NumElts->isTypeDependent() ||
1334 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001335 "Size must be type- or value-dependent!");
1336
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001337 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001338 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001339 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001340
1341 if (NumElts) {
1342 // Dependently-sized array types that do not have a specified
1343 // number of elements will have their sizes deduced from an
1344 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001345 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1346 EltTypeQuals, NumElts);
1347
1348 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1349 }
1350
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001351 DependentSizedArrayType *New;
1352 if (Canon) {
1353 // We already have a canonical version of this array type; use it as
1354 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001355 New = new (*this, TypeAlignment)
1356 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1357 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001358 } else {
1359 QualType CanonEltTy = getCanonicalType(EltTy);
1360 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001361 New = new (*this, TypeAlignment)
1362 DependentSizedArrayType(*this, EltTy, QualType(),
1363 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001364
Douglas Gregor789b1f62010-02-04 18:10:26 +00001365 if (NumElts) {
1366 DependentSizedArrayType *CanonCheck
1367 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1368 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1369 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001370 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001371 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001372 } else {
1373 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1374 ASM, EltTypeQuals,
1375 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001376 New = new (*this, TypeAlignment)
1377 DependentSizedArrayType(*this, EltTy, Canon,
1378 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001379 }
1380 }
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Douglas Gregor898574e2008-12-05 23:32:09 +00001382 Types.push_back(New);
1383 return QualType(New, 0);
1384}
1385
Eli Friedmanc5773c42008-02-15 18:16:39 +00001386QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1387 ArrayType::ArraySizeModifier ASM,
1388 unsigned EltTypeQuals) {
1389 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001390 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001391
1392 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001393 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001394 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1395 return QualType(ATP, 0);
1396
1397 // If the element type isn't canonical, this won't be a canonical type
1398 // either, so fill in the canonical type field.
1399 QualType Canonical;
1400
John McCall467b27b2009-10-22 20:10:53 +00001401 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001402 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001403 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001404
1405 // Get the new insert position for the node we care about.
1406 IncompleteArrayType *NewIP =
1407 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001408 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001409 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001410
John McCall6b304a02009-09-24 23:30:46 +00001411 IncompleteArrayType *New = new (*this, TypeAlignment)
1412 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001413
1414 IncompleteArrayTypes.InsertNode(New, InsertPos);
1415 Types.push_back(New);
1416 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001417}
1418
Steve Naroff73322922007-07-18 18:00:27 +00001419/// getVectorType - Return the unique reference to a vector type of
1420/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001421QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1422 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattnerf52ab252008-04-06 22:59:24 +00001425 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001426 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // Check if we've already instantiated a vector of this type.
1429 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001430 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1431 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 void *InsertPos = 0;
1433 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1434 return QualType(VTP, 0);
1435
1436 // If the element type isn't canonical, this won't be a canonical type either,
1437 // so fill in the canonical type field.
1438 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001439 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1440 Canonical = getVectorType(getCanonicalType(vecType),
1441 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 // Get the new insert position for the node we care about.
1444 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001445 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 }
John McCall6b304a02009-09-24 23:30:46 +00001447 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001448 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 VectorTypes.InsertNode(New, InsertPos);
1450 Types.push_back(New);
1451 return QualType(New, 0);
1452}
1453
Nate Begeman213541a2008-04-18 23:10:10 +00001454/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001455/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001456QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001457 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Chris Lattnerf52ab252008-04-06 22:59:24 +00001459 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001460 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Steve Naroff73322922007-07-18 18:00:27 +00001462 // Check if we've already instantiated a vector of this type.
1463 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001464 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001465 void *InsertPos = 0;
1466 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1467 return QualType(VTP, 0);
1468
1469 // If the element type isn't canonical, this won't be a canonical type either,
1470 // so fill in the canonical type field.
1471 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001472 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001473 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Steve Naroff73322922007-07-18 18:00:27 +00001475 // Get the new insert position for the node we care about.
1476 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001477 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001478 }
John McCall6b304a02009-09-24 23:30:46 +00001479 ExtVectorType *New = new (*this, TypeAlignment)
1480 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001481 VectorTypes.InsertNode(New, InsertPos);
1482 Types.push_back(New);
1483 return QualType(New, 0);
1484}
1485
Mike Stump1eb44332009-09-09 15:08:12 +00001486QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001487 Expr *SizeExpr,
1488 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001489 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001490 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001491 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001493 void *InsertPos = 0;
1494 DependentSizedExtVectorType *Canon
1495 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1496 DependentSizedExtVectorType *New;
1497 if (Canon) {
1498 // We already have a canonical version of this array type; use it as
1499 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001500 New = new (*this, TypeAlignment)
1501 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1502 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001503 } else {
1504 QualType CanonVecTy = getCanonicalType(vecType);
1505 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001506 New = new (*this, TypeAlignment)
1507 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1508 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001509
1510 DependentSizedExtVectorType *CanonCheck
1511 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1512 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1513 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001514 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1515 } else {
1516 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1517 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001518 New = new (*this, TypeAlignment)
1519 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001520 }
1521 }
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001523 Types.push_back(New);
1524 return QualType(New, 0);
1525}
1526
Douglas Gregor72564e72009-02-26 23:50:07 +00001527/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001528///
Rafael Espindola264ba482010-03-30 20:24:48 +00001529QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1530 const FunctionType::ExtInfo &Info) {
1531 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Unique functions, to guarantee there is only one function of a particular
1533 // structure.
1534 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001535 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001538 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001539 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001543 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001544 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001545 Canonical =
1546 getFunctionNoProtoType(getCanonicalType(ResultTy),
1547 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001550 FunctionNoProtoType *NewIP =
1551 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001552 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
John McCall6b304a02009-09-24 23:30:46 +00001555 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001556 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001558 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 return QualType(New, 0);
1560}
1561
1562/// getFunctionType - Return a normal function type with a typed argument
1563/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001564QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001565 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001566 unsigned TypeQuals, bool hasExceptionSpec,
1567 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001568 const QualType *ExArray,
1569 const FunctionType::ExtInfo &Info) {
1570 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Unique functions, to guarantee there is only one function of a particular
1572 // structure.
1573 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001574 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001575 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001576 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001577
1578 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001579 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001580 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001582
1583 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001584 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001586 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 isCanonical = false;
1588
1589 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001590 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001592 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 llvm::SmallVector<QualType, 16> CanonicalArgs;
1594 CanonicalArgs.reserve(NumArgs);
1595 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001596 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001597
Chris Lattnerf52ab252008-04-06 22:59:24 +00001598 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001599 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001600 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001601 false, 0, 0,
1602 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001603
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001605 FunctionProtoType *NewIP =
1606 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001607 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001609
Douglas Gregor72564e72009-02-26 23:50:07 +00001610 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001611 // for two variable size arrays (for parameter and exception types) at the
1612 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001613 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001614 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1615 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001616 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001617 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001618 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001619 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001621 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 return QualType(FTP, 0);
1623}
1624
John McCall3cb0ebd2010-03-10 03:28:59 +00001625#ifndef NDEBUG
1626static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1627 if (!isa<CXXRecordDecl>(D)) return false;
1628 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1629 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1630 return true;
1631 if (RD->getDescribedClassTemplate() &&
1632 !isa<ClassTemplateSpecializationDecl>(RD))
1633 return true;
1634 return false;
1635}
1636#endif
1637
1638/// getInjectedClassNameType - Return the unique reference to the
1639/// injected class name type for the specified templated declaration.
1640QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1641 QualType TST) {
1642 assert(NeedsInjectedClassNameType(Decl));
1643 if (Decl->TypeForDecl) {
1644 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1645 } else if (CXXRecordDecl *PrevDecl
1646 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1647 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1648 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1649 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1650 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001651 Decl->TypeForDecl =
1652 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001653 Types.push_back(Decl->TypeForDecl);
1654 }
1655 return QualType(Decl->TypeForDecl, 0);
1656}
1657
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001658/// getTypeDeclType - Return the unique reference to the type for the
1659/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001660QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001661 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001662 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001663
John McCall19c85762010-02-16 03:57:14 +00001664 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001665 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001666
John McCallbecb8d52010-03-10 06:48:02 +00001667 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1668 "Template type parameter types are always available.");
1669
John McCall19c85762010-02-16 03:57:14 +00001670 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001671 assert(!Record->getPreviousDeclaration() &&
1672 "struct/union has previous declaration");
1673 assert(!NeedsInjectedClassNameType(Record));
1674 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001675 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001676 assert(!Enum->getPreviousDeclaration() &&
1677 "enum has previous declaration");
1678 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001679 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001680 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1681 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001682 } else
John McCallbecb8d52010-03-10 06:48:02 +00001683 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001684
John McCallbecb8d52010-03-10 06:48:02 +00001685 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001686 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001687}
1688
Reid Spencer5f016e22007-07-11 17:01:13 +00001689/// getTypedefType - Return the unique reference to the type for the
1690/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001691QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Chris Lattnerf52ab252008-04-06 22:59:24 +00001694 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001695 Decl->TypeForDecl = new(*this, TypeAlignment)
1696 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 Types.push_back(Decl->TypeForDecl);
1698 return QualType(Decl->TypeForDecl, 0);
1699}
1700
John McCall49a832b2009-10-18 09:09:24 +00001701/// \brief Retrieve a substitution-result type.
1702QualType
1703ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1704 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001705 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001706 && "replacement types must always be canonical");
1707
1708 llvm::FoldingSetNodeID ID;
1709 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1710 void *InsertPos = 0;
1711 SubstTemplateTypeParmType *SubstParm
1712 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1713
1714 if (!SubstParm) {
1715 SubstParm = new (*this, TypeAlignment)
1716 SubstTemplateTypeParmType(Parm, Replacement);
1717 Types.push_back(SubstParm);
1718 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1719 }
1720
1721 return QualType(SubstParm, 0);
1722}
1723
Douglas Gregorfab9d672009-02-05 23:33:38 +00001724/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001725/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001726/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001727QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001728 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001729 IdentifierInfo *Name) {
1730 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001731 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001732 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001733 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001734 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1735
1736 if (TypeParm)
1737 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001739 if (Name) {
1740 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001741 TypeParm = new (*this, TypeAlignment)
1742 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001743
1744 TemplateTypeParmType *TypeCheck
1745 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1746 assert(!TypeCheck && "Template type parameter canonical type broken");
1747 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001748 } else
John McCall6b304a02009-09-24 23:30:46 +00001749 TypeParm = new (*this, TypeAlignment)
1750 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001751
1752 Types.push_back(TypeParm);
1753 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1754
1755 return QualType(TypeParm, 0);
1756}
1757
John McCall3cb0ebd2010-03-10 03:28:59 +00001758TypeSourceInfo *
1759ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1760 SourceLocation NameLoc,
1761 const TemplateArgumentListInfo &Args,
1762 QualType CanonType) {
1763 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1764
1765 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1766 TemplateSpecializationTypeLoc TL
1767 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1768 TL.setTemplateNameLoc(NameLoc);
1769 TL.setLAngleLoc(Args.getLAngleLoc());
1770 TL.setRAngleLoc(Args.getRAngleLoc());
1771 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1772 TL.setArgLocInfo(i, Args[i].getLocInfo());
1773 return DI;
1774}
1775
Mike Stump1eb44332009-09-09 15:08:12 +00001776QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001777ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001778 const TemplateArgumentListInfo &Args,
John McCall31f17ec2010-04-27 00:57:59 +00001779 QualType Canon,
1780 bool IsCurrentInstantiation) {
John McCalld5532b62009-11-23 01:53:49 +00001781 unsigned NumArgs = Args.size();
1782
John McCall833ca992009-10-29 08:12:44 +00001783 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1784 ArgVec.reserve(NumArgs);
1785 for (unsigned i = 0; i != NumArgs; ++i)
1786 ArgVec.push_back(Args[i].getArgument());
1787
John McCall31f17ec2010-04-27 00:57:59 +00001788 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1789 Canon, IsCurrentInstantiation);
John McCall833ca992009-10-29 08:12:44 +00001790}
1791
1792QualType
1793ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001794 const TemplateArgument *Args,
1795 unsigned NumArgs,
John McCall31f17ec2010-04-27 00:57:59 +00001796 QualType Canon,
1797 bool IsCurrentInstantiation) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001798 if (!Canon.isNull())
1799 Canon = getCanonicalType(Canon);
1800 else {
John McCall31f17ec2010-04-27 00:57:59 +00001801 assert(!IsCurrentInstantiation &&
1802 "current-instantiation specializations should always "
1803 "have a canonical type");
1804
Douglas Gregorb88e8882009-07-30 17:40:51 +00001805 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001806 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1807 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1808 CanonArgs.reserve(NumArgs);
1809 for (unsigned I = 0; I != NumArgs; ++I)
1810 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1811
1812 // Determine whether this canonical template specialization type already
1813 // exists.
1814 llvm::FoldingSetNodeID ID;
John McCall31f17ec2010-04-27 00:57:59 +00001815 TemplateSpecializationType::Profile(ID, CanonTemplate, false,
Douglas Gregor828e2262009-07-29 16:09:57 +00001816 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001817
1818 void *InsertPos = 0;
1819 TemplateSpecializationType *Spec
1820 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Douglas Gregor1275ae02009-07-28 23:00:59 +00001822 if (!Spec) {
1823 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001824 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001825 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001826 TypeAlignment);
John McCall31f17ec2010-04-27 00:57:59 +00001827 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, false,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001828 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001829 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001830 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001831 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001832 }
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Douglas Gregorb88e8882009-07-30 17:40:51 +00001834 if (Canon.isNull())
1835 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001836 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001837 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001838 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001839
Douglas Gregor1275ae02009-07-28 23:00:59 +00001840 // Allocate the (non-canonical) template specialization type, but don't
1841 // try to unique it: these types typically have location information that
1842 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001843 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001844 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001845 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001846 TemplateSpecializationType *Spec
John McCall31f17ec2010-04-27 00:57:59 +00001847 = new (Mem) TemplateSpecializationType(*this, Template,
1848 IsCurrentInstantiation,
1849 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001850 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Douglas Gregor55f6b142009-02-09 18:46:07 +00001852 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001853 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001854}
1855
Mike Stump1eb44332009-09-09 15:08:12 +00001856QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001857ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1858 NestedNameSpecifier *NNS,
1859 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001860 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001861 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001862
1863 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001864 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001865 if (T)
1866 return QualType(T, 0);
1867
Douglas Gregor789b1f62010-02-04 18:10:26 +00001868 QualType Canon = NamedType;
1869 if (!Canon.isCanonical()) {
1870 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001871 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1872 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001873 (void)CheckT;
1874 }
1875
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001876 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001877 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001878 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001879 return QualType(T, 0);
1880}
1881
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001882QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1883 NestedNameSpecifier *NNS,
1884 const IdentifierInfo *Name,
1885 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00001886 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1887
1888 if (Canon.isNull()) {
1889 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001890 ElaboratedTypeKeyword CanonKeyword = Keyword;
1891 if (Keyword == ETK_None)
1892 CanonKeyword = ETK_Typename;
1893
1894 if (CanonNNS != NNS || CanonKeyword != Keyword)
1895 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00001896 }
1897
1898 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001899 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00001900
1901 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00001902 DependentNameType *T
1903 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00001904 if (T)
1905 return QualType(T, 0);
1906
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001907 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00001908 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00001909 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001910 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001911}
1912
Mike Stump1eb44332009-09-09 15:08:12 +00001913QualType
John McCall33500952010-06-11 00:33:02 +00001914ASTContext::getDependentTemplateSpecializationType(
1915 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001916 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00001917 const IdentifierInfo *Name,
1918 const TemplateArgumentListInfo &Args) {
1919 // TODO: avoid this copy
1920 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
1921 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1922 ArgCopy.push_back(Args[I].getArgument());
1923 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
1924 ArgCopy.size(),
1925 ArgCopy.data());
1926}
1927
1928QualType
1929ASTContext::getDependentTemplateSpecializationType(
1930 ElaboratedTypeKeyword Keyword,
1931 NestedNameSpecifier *NNS,
1932 const IdentifierInfo *Name,
1933 unsigned NumArgs,
1934 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00001935 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1936
Douglas Gregor789b1f62010-02-04 18:10:26 +00001937 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00001938 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
1939 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001940
1941 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00001942 DependentTemplateSpecializationType *T
1943 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001944 if (T)
1945 return QualType(T, 0);
1946
John McCall33500952010-06-11 00:33:02 +00001947 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001948
John McCall33500952010-06-11 00:33:02 +00001949 ElaboratedTypeKeyword CanonKeyword = Keyword;
1950 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
1951
1952 bool AnyNonCanonArgs = false;
1953 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
1954 for (unsigned I = 0; I != NumArgs; ++I) {
1955 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
1956 if (!CanonArgs[I].structurallyEquals(Args[I]))
1957 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00001958 }
1959
John McCall33500952010-06-11 00:33:02 +00001960 QualType Canon;
1961 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
1962 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
1963 Name, NumArgs,
1964 CanonArgs.data());
1965
1966 // Find the insert position again.
1967 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1968 }
1969
1970 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
1971 sizeof(TemplateArgument) * NumArgs),
1972 TypeAlignment);
1973 T = new (Mem) DependentTemplateSpecializationType(*this, Keyword, NNS,
1974 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00001975 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00001976 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001977 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001978}
1979
Chris Lattner88cb27a2008-04-07 04:56:42 +00001980/// CmpProtocolNames - Comparison predicate for sorting protocols
1981/// alphabetically.
1982static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1983 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001984 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001985}
1986
John McCallc12c5bb2010-05-15 11:32:37 +00001987static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00001988 unsigned NumProtocols) {
1989 if (NumProtocols == 0) return true;
1990
1991 for (unsigned i = 1; i != NumProtocols; ++i)
1992 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1993 return false;
1994 return true;
1995}
1996
1997static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00001998 unsigned &NumProtocols) {
1999 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Chris Lattner88cb27a2008-04-07 04:56:42 +00002001 // Sort protocols, keyed by name.
2002 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2003
2004 // Remove duplicates.
2005 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2006 NumProtocols = ProtocolsEnd-Protocols;
2007}
2008
John McCallc12c5bb2010-05-15 11:32:37 +00002009QualType ASTContext::getObjCObjectType(QualType BaseType,
2010 ObjCProtocolDecl * const *Protocols,
2011 unsigned NumProtocols) {
2012 // If the base type is an interface and there aren't any protocols
2013 // to add, then the interface type will do just fine.
2014 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2015 return BaseType;
2016
2017 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002018 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002019 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002020 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002021 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2022 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002023
John McCallc12c5bb2010-05-15 11:32:37 +00002024 // Build the canonical type, which has the canonical base type and
2025 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002026 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002027 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2028 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2029 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002030 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2031 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002032 unsigned UniqueCount = NumProtocols;
2033
John McCall54e14c42009-10-22 22:37:11 +00002034 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002035 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2036 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002037 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002038 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2039 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002040 }
2041
2042 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002043 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2044 }
2045
2046 unsigned Size = sizeof(ObjCObjectTypeImpl);
2047 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2048 void *Mem = Allocate(Size, TypeAlignment);
2049 ObjCObjectTypeImpl *T =
2050 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2051
2052 Types.push_back(T);
2053 ObjCObjectTypes.InsertNode(T, InsertPos);
2054 return QualType(T, 0);
2055}
2056
2057/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2058/// the given object type.
2059QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2060 llvm::FoldingSetNodeID ID;
2061 ObjCObjectPointerType::Profile(ID, ObjectT);
2062
2063 void *InsertPos = 0;
2064 if (ObjCObjectPointerType *QT =
2065 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2066 return QualType(QT, 0);
2067
2068 // Find the canonical object type.
2069 QualType Canonical;
2070 if (!ObjectT.isCanonical()) {
2071 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2072
2073 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002074 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2075 }
2076
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002077 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002078 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2079 ObjCObjectPointerType *QType =
2080 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002082 Types.push_back(QType);
2083 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002084 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002085}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002086
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002087/// getObjCInterfaceType - Return the unique reference to the type for the
2088/// specified ObjC interface decl. The list of protocols is optional.
John McCallc12c5bb2010-05-15 11:32:37 +00002089QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2090 if (Decl->TypeForDecl)
2091 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002092
John McCallc12c5bb2010-05-15 11:32:37 +00002093 // FIXME: redeclarations?
2094 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2095 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2096 Decl->TypeForDecl = T;
2097 Types.push_back(T);
2098 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002099}
2100
Douglas Gregor72564e72009-02-26 23:50:07 +00002101/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2102/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002103/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002104/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002105/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002106QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002107 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002108 if (tofExpr->isTypeDependent()) {
2109 llvm::FoldingSetNodeID ID;
2110 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Douglas Gregorb1975722009-07-30 23:18:24 +00002112 void *InsertPos = 0;
2113 DependentTypeOfExprType *Canon
2114 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2115 if (Canon) {
2116 // We already have a "canonical" version of an identical, dependent
2117 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002118 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002119 QualType((TypeOfExprType*)Canon, 0));
2120 }
2121 else {
2122 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002123 Canon
2124 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002125 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2126 toe = Canon;
2127 }
2128 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002129 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002130 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002131 }
Steve Naroff9752f252007-08-01 18:02:17 +00002132 Types.push_back(toe);
2133 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002134}
2135
Steve Naroff9752f252007-08-01 18:02:17 +00002136/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2137/// TypeOfType AST's. The only motivation to unique these nodes would be
2138/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002139/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002140/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002141QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002142 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002143 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002144 Types.push_back(tot);
2145 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002146}
2147
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002148/// getDecltypeForExpr - Given an expr, will return the decltype for that
2149/// expression, according to the rules in C++0x [dcl.type.simple]p4
2150static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002151 if (e->isTypeDependent())
2152 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002154 // If e is an id expression or a class member access, decltype(e) is defined
2155 // as the type of the entity named by e.
2156 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2157 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2158 return VD->getType();
2159 }
2160 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2161 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2162 return FD->getType();
2163 }
2164 // If e is a function call or an invocation of an overloaded operator,
2165 // (parentheses around e are ignored), decltype(e) is defined as the
2166 // return type of that function.
2167 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2168 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002170 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002171
2172 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002173 // defined as T&, otherwise decltype(e) is defined as T.
2174 if (e->isLvalue(Context) == Expr::LV_Valid)
2175 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002177 return T;
2178}
2179
Anders Carlsson395b4752009-06-24 19:06:50 +00002180/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2181/// DecltypeType AST's. The only motivation to unique these nodes would be
2182/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002183/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002184/// on canonical type's (which are always unique).
2185QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002186 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002187 if (e->isTypeDependent()) {
2188 llvm::FoldingSetNodeID ID;
2189 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002191 void *InsertPos = 0;
2192 DependentDecltypeType *Canon
2193 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2194 if (Canon) {
2195 // We already have a "canonical" version of an equivalent, dependent
2196 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002197 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002198 QualType((DecltypeType*)Canon, 0));
2199 }
2200 else {
2201 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002202 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002203 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2204 dt = Canon;
2205 }
2206 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002207 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002208 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002209 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002210 Types.push_back(dt);
2211 return QualType(dt, 0);
2212}
2213
Reid Spencer5f016e22007-07-11 17:01:13 +00002214/// getTagDeclType - Return the unique reference to the type for the
2215/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002216QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002217 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002218 // FIXME: What is the design on getTagDeclType when it requires casting
2219 // away const? mutable?
2220 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002221}
2222
Mike Stump1eb44332009-09-09 15:08:12 +00002223/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2224/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2225/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002226CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002227 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002228}
2229
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002230/// getSignedWCharType - Return the type of "signed wchar_t".
2231/// Used when in C++, as a GCC extension.
2232QualType ASTContext::getSignedWCharType() const {
2233 // FIXME: derive from "Target" ?
2234 return WCharTy;
2235}
2236
2237/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2238/// Used when in C++, as a GCC extension.
2239QualType ASTContext::getUnsignedWCharType() const {
2240 // FIXME: derive from "Target" ?
2241 return UnsignedIntTy;
2242}
2243
Chris Lattner8b9023b2007-07-13 03:05:23 +00002244/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2245/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2246QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002247 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002248}
2249
Chris Lattnere6327742008-04-02 05:18:44 +00002250//===----------------------------------------------------------------------===//
2251// Type Operators
2252//===----------------------------------------------------------------------===//
2253
John McCall54e14c42009-10-22 22:37:11 +00002254CanQualType ASTContext::getCanonicalParamType(QualType T) {
2255 // Push qualifiers into arrays, and then discard any remaining
2256 // qualifiers.
2257 T = getCanonicalType(T);
2258 const Type *Ty = T.getTypePtr();
2259
2260 QualType Result;
2261 if (isa<ArrayType>(Ty)) {
2262 Result = getArrayDecayedType(QualType(Ty,0));
2263 } else if (isa<FunctionType>(Ty)) {
2264 Result = getPointerType(QualType(Ty, 0));
2265 } else {
2266 Result = QualType(Ty, 0);
2267 }
2268
2269 return CanQualType::CreateUnsafe(Result);
2270}
2271
Chris Lattner77c96472008-04-06 22:41:35 +00002272/// getCanonicalType - Return the canonical (structural) type corresponding to
2273/// the specified potentially non-canonical type. The non-canonical version
2274/// of a type may have many "decorated" versions of types. Decorators can
2275/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2276/// to be free of any of these, allowing two canonical types to be compared
2277/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002278CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002279 QualifierCollector Quals;
2280 const Type *Ptr = Quals.strip(T);
2281 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002282
John McCall0953e762009-09-24 19:53:00 +00002283 // The canonical internal type will be the canonical type *except*
2284 // that we push type qualifiers down through array types.
2285
2286 // If there are no new qualifiers to push down, stop here.
2287 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002288 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002289
John McCall0953e762009-09-24 19:53:00 +00002290 // If the type qualifiers are on an array type, get the canonical
2291 // type of the array with the qualifiers applied to the element
2292 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002293 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2294 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002295 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002297 // Get the canonical version of the element with the extra qualifiers on it.
2298 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002299 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002300 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002302 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002303 return CanQualType::CreateUnsafe(
2304 getConstantArrayType(NewEltTy, CAT->getSize(),
2305 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002306 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002307 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002308 return CanQualType::CreateUnsafe(
2309 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002310 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregor898574e2008-12-05 23:32:09 +00002312 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002313 return CanQualType::CreateUnsafe(
2314 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002315 DSAT->getSizeExpr() ?
2316 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002317 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002318 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002319 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002320
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002321 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002322 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002323 VAT->getSizeExpr() ?
2324 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002325 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002326 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002327 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002328}
2329
Chandler Carruth28e318c2009-12-29 07:16:59 +00002330QualType ASTContext::getUnqualifiedArrayType(QualType T,
2331 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002332 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002333 const ArrayType *AT = getAsArrayType(T);
2334 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002335 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002336 }
2337
Chandler Carruth28e318c2009-12-29 07:16:59 +00002338 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002339 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002340 if (Elt == UnqualElt)
2341 return T;
2342
Douglas Gregor9dadd942010-05-17 18:45:21 +00002343 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002344 return getConstantArrayType(UnqualElt, CAT->getSize(),
2345 CAT->getSizeModifier(), 0);
2346 }
2347
Douglas Gregor9dadd942010-05-17 18:45:21 +00002348 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002349 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2350 }
2351
Douglas Gregor9dadd942010-05-17 18:45:21 +00002352 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2353 return getVariableArrayType(UnqualElt,
2354 VAT->getSizeExpr() ?
2355 VAT->getSizeExpr()->Retain() : 0,
2356 VAT->getSizeModifier(),
2357 VAT->getIndexTypeCVRQualifiers(),
2358 VAT->getBracketsRange());
2359 }
2360
2361 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002362 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2363 DSAT->getSizeModifier(), 0,
2364 SourceRange());
2365}
2366
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002367/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2368/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2369/// they point to and return true. If T1 and T2 aren't pointer types
2370/// or pointer-to-member types, or if they are not similar at this
2371/// level, returns false and leaves T1 and T2 unchanged. Top-level
2372/// qualifiers on T1 and T2 are ignored. This function will typically
2373/// be called in a loop that successively "unwraps" pointer and
2374/// pointer-to-member types to compare them at each level.
2375bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2376 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2377 *T2PtrType = T2->getAs<PointerType>();
2378 if (T1PtrType && T2PtrType) {
2379 T1 = T1PtrType->getPointeeType();
2380 T2 = T2PtrType->getPointeeType();
2381 return true;
2382 }
2383
2384 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2385 *T2MPType = T2->getAs<MemberPointerType>();
2386 if (T1MPType && T2MPType &&
2387 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2388 QualType(T2MPType->getClass(), 0))) {
2389 T1 = T1MPType->getPointeeType();
2390 T2 = T2MPType->getPointeeType();
2391 return true;
2392 }
2393
2394 if (getLangOptions().ObjC1) {
2395 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2396 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2397 if (T1OPType && T2OPType) {
2398 T1 = T1OPType->getPointeeType();
2399 T2 = T2OPType->getPointeeType();
2400 return true;
2401 }
2402 }
2403
2404 // FIXME: Block pointers, too?
2405
2406 return false;
2407}
2408
John McCall80ad16f2009-11-24 18:42:40 +00002409DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2410 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2411 return TD->getDeclName();
2412
2413 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2414 if (DTN->isIdentifier()) {
2415 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2416 } else {
2417 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2418 }
2419 }
2420
John McCall0bd6feb2009-12-02 08:04:21 +00002421 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2422 assert(Storage);
2423 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002424}
2425
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002426TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2427 // If this template name refers to a template, the canonical
2428 // template name merely stores the template itself.
2429 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002430 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002431
John McCall0bd6feb2009-12-02 08:04:21 +00002432 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002434 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2435 assert(DTN && "Non-dependent template names must refer to template decls.");
2436 return DTN->CanonicalTemplateName;
2437}
2438
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002439bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2440 X = getCanonicalTemplateName(X);
2441 Y = getCanonicalTemplateName(Y);
2442 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2443}
2444
Mike Stump1eb44332009-09-09 15:08:12 +00002445TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002446ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2447 switch (Arg.getKind()) {
2448 case TemplateArgument::Null:
2449 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Douglas Gregor1275ae02009-07-28 23:00:59 +00002451 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002452 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Douglas Gregor1275ae02009-07-28 23:00:59 +00002454 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002455 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Douglas Gregor788cd062009-11-11 01:00:40 +00002457 case TemplateArgument::Template:
2458 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2459
Douglas Gregor1275ae02009-07-28 23:00:59 +00002460 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002461 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002462 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Douglas Gregor1275ae02009-07-28 23:00:59 +00002464 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002465 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Douglas Gregor1275ae02009-07-28 23:00:59 +00002467 case TemplateArgument::Pack: {
2468 // FIXME: Allocate in ASTContext
2469 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2470 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002471 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002472 AEnd = Arg.pack_end();
2473 A != AEnd; (void)++A, ++Idx)
2474 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002475
Douglas Gregor1275ae02009-07-28 23:00:59 +00002476 TemplateArgument Result;
2477 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2478 return Result;
2479 }
2480 }
2481
2482 // Silence GCC warning
2483 assert(false && "Unhandled template argument kind");
2484 return TemplateArgument();
2485}
2486
Douglas Gregord57959a2009-03-27 23:10:48 +00002487NestedNameSpecifier *
2488ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002489 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002490 return 0;
2491
2492 switch (NNS->getKind()) {
2493 case NestedNameSpecifier::Identifier:
2494 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002495 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002496 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2497 NNS->getAsIdentifier());
2498
2499 case NestedNameSpecifier::Namespace:
2500 // A namespace is canonical; build a nested-name-specifier with
2501 // this namespace and no prefix.
2502 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2503
2504 case NestedNameSpecifier::TypeSpec:
2505 case NestedNameSpecifier::TypeSpecWithTemplate: {
2506 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002507 return NestedNameSpecifier::Create(*this, 0,
2508 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002509 T.getTypePtr());
2510 }
2511
2512 case NestedNameSpecifier::Global:
2513 // The global specifier is canonical and unique.
2514 return NNS;
2515 }
2516
2517 // Required to silence a GCC warning
2518 return 0;
2519}
2520
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521
2522const ArrayType *ASTContext::getAsArrayType(QualType T) {
2523 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002524 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002525 // Handle the common positive case fast.
2526 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2527 return AT;
2528 }
Mike Stump1eb44332009-09-09 15:08:12 +00002529
John McCall0953e762009-09-24 19:53:00 +00002530 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002531 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002532 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002533 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002534
John McCall0953e762009-09-24 19:53:00 +00002535 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002536 // implements C99 6.7.3p8: "If the specification of an array type includes
2537 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002539 // If we get here, we either have type qualifiers on the type, or we have
2540 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002541 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002542
John McCall0953e762009-09-24 19:53:00 +00002543 QualifierCollector Qs;
2544 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002546 // If we have a simple case, just return now.
2547 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002548 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002549 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002551 // Otherwise, we have an array and we have qualifiers on it. Push the
2552 // qualifiers into the array element type and return a new array type.
2553 // Get the canonical version of the element with the extra qualifiers on it.
2554 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002555 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002556
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002557 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2558 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2559 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002560 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002561 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2562 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2563 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002564 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002565
Mike Stump1eb44332009-09-09 15:08:12 +00002566 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002567 = dyn_cast<DependentSizedArrayType>(ATy))
2568 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002569 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002570 DSAT->getSizeExpr() ?
2571 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002572 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002573 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002574 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002576 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002577 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002578 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002579 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002580 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002581 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002582 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002583}
2584
2585
Chris Lattnere6327742008-04-02 05:18:44 +00002586/// getArrayDecayedType - Return the properly qualified result of decaying the
2587/// specified array type to a pointer. This operation is non-trivial when
2588/// handling typedefs etc. The canonical type of "T" must be an array type,
2589/// this returns a pointer to a properly qualified element of the array.
2590///
2591/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2592QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002593 // Get the element type with 'getAsArrayType' so that we don't lose any
2594 // typedefs in the element type of the array. This also handles propagation
2595 // of type qualifiers from the array type into the element type if present
2596 // (C99 6.7.3p8).
2597 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2598 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002600 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002601
2602 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002603 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002604}
2605
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002606QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002607 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002608 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2609 QT = AT->getElementType();
2610 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002611}
2612
Anders Carlssonfbbce492009-09-25 01:23:32 +00002613QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2614 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Anders Carlssonfbbce492009-09-25 01:23:32 +00002616 if (const ArrayType *AT = getAsArrayType(ElemTy))
2617 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Anders Carlsson6183a992008-12-21 03:44:36 +00002619 return ElemTy;
2620}
2621
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002622/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002623uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002624ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2625 uint64_t ElementCount = 1;
2626 do {
2627 ElementCount *= CA->getSize().getZExtValue();
2628 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2629 } while (CA);
2630 return ElementCount;
2631}
2632
Reid Spencer5f016e22007-07-11 17:01:13 +00002633/// getFloatingRank - Return a relative rank for floating point types.
2634/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002635static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002636 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002638
John McCall183700f2009-09-21 23:43:11 +00002639 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2640 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002641 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 case BuiltinType::Float: return FloatRank;
2643 case BuiltinType::Double: return DoubleRank;
2644 case BuiltinType::LongDouble: return LongDoubleRank;
2645 }
2646}
2647
Mike Stump1eb44332009-09-09 15:08:12 +00002648/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2649/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002650/// 'typeDomain' is a real floating point or complex type.
2651/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002652QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2653 QualType Domain) const {
2654 FloatingRank EltRank = getFloatingRank(Size);
2655 if (Domain->isComplexType()) {
2656 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002657 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002658 case FloatRank: return FloatComplexTy;
2659 case DoubleRank: return DoubleComplexTy;
2660 case LongDoubleRank: return LongDoubleComplexTy;
2661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 }
Chris Lattner1361b112008-04-06 23:58:54 +00002663
2664 assert(Domain->isRealFloatingType() && "Unknown domain!");
2665 switch (EltRank) {
2666 default: assert(0 && "getFloatingRank(): illegal value for rank");
2667 case FloatRank: return FloatTy;
2668 case DoubleRank: return DoubleTy;
2669 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002671}
2672
Chris Lattner7cfeb082008-04-06 23:55:33 +00002673/// getFloatingTypeOrder - Compare the rank of the two specified floating
2674/// point types, ignoring the domain of the type (i.e. 'double' ==
2675/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002676/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002677int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2678 FloatingRank LHSR = getFloatingRank(LHS);
2679 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattnera75cea32008-04-06 23:38:49 +00002681 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002682 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002683 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002684 return 1;
2685 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002686}
2687
Chris Lattnerf52ab252008-04-06 22:59:24 +00002688/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2689/// routine will assert if passed a built-in type that isn't an integer or enum,
2690/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002691unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002692 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002693 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002694 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002695
Eli Friedmana3426752009-07-05 23:44:27 +00002696 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2697 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2698
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002699 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2700 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2701
2702 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2703 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2704
Chris Lattnerf52ab252008-04-06 22:59:24 +00002705 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002706 default: assert(0 && "getIntegerRank(): not a built-in integer");
2707 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002708 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002709 case BuiltinType::Char_S:
2710 case BuiltinType::Char_U:
2711 case BuiltinType::SChar:
2712 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002713 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002714 case BuiltinType::Short:
2715 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002716 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002717 case BuiltinType::Int:
2718 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002719 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002720 case BuiltinType::Long:
2721 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002722 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002723 case BuiltinType::LongLong:
2724 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002725 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002726 case BuiltinType::Int128:
2727 case BuiltinType::UInt128:
2728 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002729 }
2730}
2731
Eli Friedman04e83572009-08-20 04:21:42 +00002732/// \brief Whether this is a promotable bitfield reference according
2733/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2734///
2735/// \returns the type this bit-field will promote to, or NULL if no
2736/// promotion occurs.
2737QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002738 if (E->isTypeDependent() || E->isValueDependent())
2739 return QualType();
2740
Eli Friedman04e83572009-08-20 04:21:42 +00002741 FieldDecl *Field = E->getBitField();
2742 if (!Field)
2743 return QualType();
2744
2745 QualType FT = Field->getType();
2746
2747 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2748 uint64_t BitWidth = BitWidthAP.getZExtValue();
2749 uint64_t IntSize = getTypeSize(IntTy);
2750 // GCC extension compatibility: if the bit-field size is less than or equal
2751 // to the size of int, it gets promoted no matter what its type is.
2752 // For instance, unsigned long bf : 4 gets promoted to signed int.
2753 if (BitWidth < IntSize)
2754 return IntTy;
2755
2756 if (BitWidth == IntSize)
2757 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2758
2759 // Types bigger than int are not subject to promotions, and therefore act
2760 // like the base type.
2761 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2762 // is ridiculous.
2763 return QualType();
2764}
2765
Eli Friedmana95d7572009-08-19 07:44:53 +00002766/// getPromotedIntegerType - Returns the type that Promotable will
2767/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2768/// integer type.
2769QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2770 assert(!Promotable.isNull());
2771 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002772 if (const EnumType *ET = Promotable->getAs<EnumType>())
2773 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002774 if (Promotable->isSignedIntegerType())
2775 return IntTy;
2776 uint64_t PromotableSize = getTypeSize(Promotable);
2777 uint64_t IntSize = getTypeSize(IntTy);
2778 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2779 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2780}
2781
Mike Stump1eb44332009-09-09 15:08:12 +00002782/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002783/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002784/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002785int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002786 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2787 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002788 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Chris Lattnerf52ab252008-04-06 22:59:24 +00002790 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2791 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Chris Lattner7cfeb082008-04-06 23:55:33 +00002793 unsigned LHSRank = getIntegerRank(LHSC);
2794 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Chris Lattner7cfeb082008-04-06 23:55:33 +00002796 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2797 if (LHSRank == RHSRank) return 0;
2798 return LHSRank > RHSRank ? 1 : -1;
2799 }
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Chris Lattner7cfeb082008-04-06 23:55:33 +00002801 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2802 if (LHSUnsigned) {
2803 // If the unsigned [LHS] type is larger, return it.
2804 if (LHSRank >= RHSRank)
2805 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Chris Lattner7cfeb082008-04-06 23:55:33 +00002807 // If the signed type can represent all values of the unsigned type, it
2808 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002809 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002810 return -1;
2811 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002812
Chris Lattner7cfeb082008-04-06 23:55:33 +00002813 // If the unsigned [RHS] type is larger, return it.
2814 if (RHSRank >= LHSRank)
2815 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Chris Lattner7cfeb082008-04-06 23:55:33 +00002817 // If the signed type can represent all values of the unsigned type, it
2818 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002819 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002820 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002821}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002822
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002823static RecordDecl *
2824CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2825 SourceLocation L, IdentifierInfo *Id) {
2826 if (Ctx.getLangOptions().CPlusPlus)
2827 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2828 else
2829 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2830}
2831
Mike Stump1eb44332009-09-09 15:08:12 +00002832// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002833QualType ASTContext::getCFConstantStringType() {
2834 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002835 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002836 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002837 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002838 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002839
Anders Carlssonf06273f2007-11-19 00:25:30 +00002840 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Anders Carlsson71993dd2007-08-17 05:31:46 +00002842 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002843 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002844 // int flags;
2845 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002846 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002847 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002848 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002849 FieldTypes[3] = LongTy;
2850
Anders Carlsson71993dd2007-08-17 05:31:46 +00002851 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002852 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002853 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002854 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002855 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002856 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002857 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002858 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002859 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002860 }
2861
Douglas Gregor838db382010-02-11 01:19:42 +00002862 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002863 }
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Anders Carlsson71993dd2007-08-17 05:31:46 +00002865 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002866}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002867
Douglas Gregor319ac892009-04-23 22:29:11 +00002868void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002869 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002870 assert(Rec && "Invalid CFConstantStringType");
2871 CFConstantStringTypeDecl = Rec->getDecl();
2872}
2873
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002874// getNSConstantStringType - Return the type used for constant NSStrings.
2875QualType ASTContext::getNSConstantStringType() {
2876 if (!NSConstantStringTypeDecl) {
2877 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002878 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002879 &Idents.get("__builtin_NSString"));
2880 NSConstantStringTypeDecl->startDefinition();
2881
2882 QualType FieldTypes[3];
2883
2884 // const int *isa;
2885 FieldTypes[0] = getPointerType(IntTy.withConst());
2886 // const char *str;
2887 FieldTypes[1] = getPointerType(CharTy.withConst());
2888 // unsigned int length;
2889 FieldTypes[2] = UnsignedIntTy;
2890
2891 // Create fields
2892 for (unsigned i = 0; i < 3; ++i) {
2893 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2894 SourceLocation(), 0,
2895 FieldTypes[i], /*TInfo=*/0,
2896 /*BitWidth=*/0,
2897 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002898 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002899 NSConstantStringTypeDecl->addDecl(Field);
2900 }
2901
2902 NSConstantStringTypeDecl->completeDefinition();
2903 }
2904
2905 return getTagDeclType(NSConstantStringTypeDecl);
2906}
2907
2908void ASTContext::setNSConstantStringType(QualType T) {
2909 const RecordType *Rec = T->getAs<RecordType>();
2910 assert(Rec && "Invalid NSConstantStringType");
2911 NSConstantStringTypeDecl = Rec->getDecl();
2912}
2913
Mike Stump1eb44332009-09-09 15:08:12 +00002914QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002915 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002916 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002917 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002918 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002919 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002921 QualType FieldTypes[] = {
2922 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002923 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002924 getPointerType(UnsignedLongTy),
2925 getConstantArrayType(UnsignedLongTy,
2926 llvm::APInt(32, 5), ArrayType::Normal, 0)
2927 };
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Douglas Gregor44b43212008-12-11 16:49:14 +00002929 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002930 FieldDecl *Field = FieldDecl::Create(*this,
2931 ObjCFastEnumerationStateTypeDecl,
2932 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002933 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002934 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002935 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002936 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002937 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002938 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00002939 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00002940 if (CXXRecordDecl *CXXRD =
2941 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00002942 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregor838db382010-02-11 01:19:42 +00002944 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002945 }
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002947 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2948}
2949
Mike Stumpadaaad32009-10-20 02:12:22 +00002950QualType ASTContext::getBlockDescriptorType() {
2951 if (BlockDescriptorType)
2952 return getTagDeclType(BlockDescriptorType);
2953
2954 RecordDecl *T;
2955 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002956 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002957 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00002958 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002959
2960 QualType FieldTypes[] = {
2961 UnsignedLongTy,
2962 UnsignedLongTy,
2963 };
2964
2965 const char *FieldNames[] = {
2966 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002967 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002968 };
2969
2970 for (size_t i = 0; i < 2; ++i) {
2971 FieldDecl *Field = FieldDecl::Create(*this,
2972 T,
2973 SourceLocation(),
2974 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002975 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002976 /*BitWidth=*/0,
2977 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002978 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00002979 T->addDecl(Field);
2980 }
2981
Douglas Gregor838db382010-02-11 01:19:42 +00002982 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002983
2984 BlockDescriptorType = T;
2985
2986 return getTagDeclType(BlockDescriptorType);
2987}
2988
2989void ASTContext::setBlockDescriptorType(QualType T) {
2990 const RecordType *Rec = T->getAs<RecordType>();
2991 assert(Rec && "Invalid BlockDescriptorType");
2992 BlockDescriptorType = Rec->getDecl();
2993}
2994
Mike Stump083c25e2009-10-22 00:49:09 +00002995QualType ASTContext::getBlockDescriptorExtendedType() {
2996 if (BlockDescriptorExtendedType)
2997 return getTagDeclType(BlockDescriptorExtendedType);
2998
2999 RecordDecl *T;
3000 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003001 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003002 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003003 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003004
3005 QualType FieldTypes[] = {
3006 UnsignedLongTy,
3007 UnsignedLongTy,
3008 getPointerType(VoidPtrTy),
3009 getPointerType(VoidPtrTy)
3010 };
3011
3012 const char *FieldNames[] = {
3013 "reserved",
3014 "Size",
3015 "CopyFuncPtr",
3016 "DestroyFuncPtr"
3017 };
3018
3019 for (size_t i = 0; i < 4; ++i) {
3020 FieldDecl *Field = FieldDecl::Create(*this,
3021 T,
3022 SourceLocation(),
3023 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003024 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003025 /*BitWidth=*/0,
3026 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003027 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003028 T->addDecl(Field);
3029 }
3030
Douglas Gregor838db382010-02-11 01:19:42 +00003031 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003032
3033 BlockDescriptorExtendedType = T;
3034
3035 return getTagDeclType(BlockDescriptorExtendedType);
3036}
3037
3038void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3039 const RecordType *Rec = T->getAs<RecordType>();
3040 assert(Rec && "Invalid BlockDescriptorType");
3041 BlockDescriptorExtendedType = Rec->getDecl();
3042}
3043
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003044bool ASTContext::BlockRequiresCopying(QualType Ty) {
3045 if (Ty->isBlockPointerType())
3046 return true;
3047 if (isObjCNSObjectType(Ty))
3048 return true;
3049 if (Ty->isObjCObjectPointerType())
3050 return true;
3051 return false;
3052}
3053
3054QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3055 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003056 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003057 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003058 // unsigned int __flags;
3059 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003060 // void *__copy_helper; // as needed
3061 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003062 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003063 // } *
3064
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003065 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3066
3067 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003068 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003069 llvm::SmallString<36> Name;
3070 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3071 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003072 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003073 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003074 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003075 T->startDefinition();
3076 QualType Int32Ty = IntTy;
3077 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3078 QualType FieldTypes[] = {
3079 getPointerType(VoidPtrTy),
3080 getPointerType(getTagDeclType(T)),
3081 Int32Ty,
3082 Int32Ty,
3083 getPointerType(VoidPtrTy),
3084 getPointerType(VoidPtrTy),
3085 Ty
3086 };
3087
3088 const char *FieldNames[] = {
3089 "__isa",
3090 "__forwarding",
3091 "__flags",
3092 "__size",
3093 "__copy_helper",
3094 "__destroy_helper",
3095 DeclName,
3096 };
3097
3098 for (size_t i = 0; i < 7; ++i) {
3099 if (!HasCopyAndDispose && i >=4 && i <= 5)
3100 continue;
3101 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3102 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003103 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003104 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003105 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003106 T->addDecl(Field);
3107 }
3108
Douglas Gregor838db382010-02-11 01:19:42 +00003109 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003110
3111 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003112}
3113
3114
3115QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003116 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003117 llvm::SmallVectorImpl<const Expr *> &Layout) {
3118
Mike Stumpadaaad32009-10-20 02:12:22 +00003119 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003120 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003121 llvm::SmallString<36> Name;
3122 llvm::raw_svector_ostream(Name) << "__block_literal_"
3123 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003124 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003125 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003126 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003127 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003128 QualType FieldTypes[] = {
3129 getPointerType(VoidPtrTy),
3130 IntTy,
3131 IntTy,
3132 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003133 (BlockHasCopyDispose ?
3134 getPointerType(getBlockDescriptorExtendedType()) :
3135 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003136 };
3137
3138 const char *FieldNames[] = {
3139 "__isa",
3140 "__flags",
3141 "__reserved",
3142 "__FuncPtr",
3143 "__descriptor"
3144 };
3145
3146 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003147 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003148 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003149 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003150 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003151 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003152 T->addDecl(Field);
3153 }
3154
John McCallea1471e2010-05-20 01:18:31 +00003155 for (unsigned i = 0; i < Layout.size(); ++i) {
3156 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003157
John McCallea1471e2010-05-20 01:18:31 +00003158 QualType FieldType = E->getType();
3159 IdentifierInfo *FieldName = 0;
3160 if (isa<CXXThisExpr>(E)) {
3161 FieldName = &Idents.get("this");
3162 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3163 const ValueDecl *D = BDRE->getDecl();
3164 FieldName = D->getIdentifier();
3165 if (BDRE->isByRef())
3166 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3167 } else {
3168 // Padding.
3169 assert(isa<ConstantArrayType>(FieldType) &&
3170 isa<DeclRefExpr>(E) &&
3171 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3172 "doesn't match characteristics of padding decl");
3173 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003174
3175 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003176 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003177 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003178 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003179 T->addDecl(Field);
3180 }
3181
Douglas Gregor838db382010-02-11 01:19:42 +00003182 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003183
3184 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003185}
3186
Douglas Gregor319ac892009-04-23 22:29:11 +00003187void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003188 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003189 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3190 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3191}
3192
Anders Carlssone8c49532007-10-29 06:33:42 +00003193// This returns true if a type has been typedefed to BOOL:
3194// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003195static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003196 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003197 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3198 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003199
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003200 return false;
3201}
3202
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003203/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003204/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003205CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003206 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003208 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003209 if (sz.isPositive() && type->isIntegralType())
3210 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003211 // Treat arrays as pointers, since that's how they're passed in.
3212 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003213 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003214 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003215}
3216
3217static inline
3218std::string charUnitsToString(const CharUnits &CU) {
3219 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003220}
3221
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003222/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003223/// declaration.
3224void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3225 std::string& S) {
3226 const BlockDecl *Decl = Expr->getBlockDecl();
3227 QualType BlockTy =
3228 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3229 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003230 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003231 // Compute size of all parameters.
3232 // Start with computing size of a pointer in number of bytes.
3233 // FIXME: There might(should) be a better way of doing this computation!
3234 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003235 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3236 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003237 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003238 E = Decl->param_end(); PI != E; ++PI) {
3239 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003240 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003241 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003242 ParmOffset += sz;
3243 }
3244 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003245 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003246 // Block pointer and offset.
3247 S += "@?0";
3248 ParmOffset = PtrSize;
3249
3250 // Argument types.
3251 ParmOffset = PtrSize;
3252 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3253 Decl->param_end(); PI != E; ++PI) {
3254 ParmVarDecl *PVDecl = *PI;
3255 QualType PType = PVDecl->getOriginalType();
3256 if (const ArrayType *AT =
3257 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3258 // Use array's original type only if it has known number of
3259 // elements.
3260 if (!isa<ConstantArrayType>(AT))
3261 PType = PVDecl->getType();
3262 } else if (PType->isFunctionType())
3263 PType = PVDecl->getType();
3264 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003265 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003266 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003267 }
3268}
3269
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003270/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003271/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003272void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003273 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003274 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003275 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003276 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003277 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003278 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003279 // Compute size of all parameters.
3280 // Start with computing size of a pointer in number of bytes.
3281 // FIXME: There might(should) be a better way of doing this computation!
3282 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003283 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003284 // The first two arguments (self and _cmd) are pointers; account for
3285 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003286 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003287 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003288 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003289 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003290 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003291 assert (sz.isPositive() &&
3292 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003293 ParmOffset += sz;
3294 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003295 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003296 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003297 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003299 // Argument types.
3300 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003301 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003302 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003303 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003304 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003305 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003306 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3307 // Use array's original type only if it has known number of
3308 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003309 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003310 PType = PVDecl->getType();
3311 } else if (PType->isFunctionType())
3312 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003313 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003314 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003315 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003316 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003317 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003318 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003319 }
3320}
3321
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003322/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003323/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003324/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3325/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003326/// Property attributes are stored as a comma-delimited C string. The simple
3327/// attributes readonly and bycopy are encoded as single characters. The
3328/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3329/// encoded as single characters, followed by an identifier. Property types
3330/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003331/// these attributes are defined by the following enumeration:
3332/// @code
3333/// enum PropertyAttributes {
3334/// kPropertyReadOnly = 'R', // property is read-only.
3335/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3336/// kPropertyByref = '&', // property is a reference to the value last assigned
3337/// kPropertyDynamic = 'D', // property is dynamic
3338/// kPropertyGetter = 'G', // followed by getter selector name
3339/// kPropertySetter = 'S', // followed by setter selector name
3340/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3341/// kPropertyType = 't' // followed by old-style type encoding.
3342/// kPropertyWeak = 'W' // 'weak' property
3343/// kPropertyStrong = 'P' // property GC'able
3344/// kPropertyNonAtomic = 'N' // property non-atomic
3345/// };
3346/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003347void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003348 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003349 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003350 // Collect information from the property implementation decl(s).
3351 bool Dynamic = false;
3352 ObjCPropertyImplDecl *SynthesizePID = 0;
3353
3354 // FIXME: Duplicated code due to poor abstraction.
3355 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003356 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003357 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3358 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003359 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003360 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003361 ObjCPropertyImplDecl *PID = *i;
3362 if (PID->getPropertyDecl() == PD) {
3363 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3364 Dynamic = true;
3365 } else {
3366 SynthesizePID = PID;
3367 }
3368 }
3369 }
3370 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003371 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003372 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003373 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003374 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003375 ObjCPropertyImplDecl *PID = *i;
3376 if (PID->getPropertyDecl() == PD) {
3377 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3378 Dynamic = true;
3379 } else {
3380 SynthesizePID = PID;
3381 }
3382 }
Mike Stump1eb44332009-09-09 15:08:12 +00003383 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003384 }
3385 }
3386
3387 // FIXME: This is not very efficient.
3388 S = "T";
3389
3390 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003391 // GCC has some special rules regarding encoding of properties which
3392 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003393 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003394 true /* outermost type */,
3395 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003396
3397 if (PD->isReadOnly()) {
3398 S += ",R";
3399 } else {
3400 switch (PD->getSetterKind()) {
3401 case ObjCPropertyDecl::Assign: break;
3402 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003403 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003404 }
3405 }
3406
3407 // It really isn't clear at all what this means, since properties
3408 // are "dynamic by default".
3409 if (Dynamic)
3410 S += ",D";
3411
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003412 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3413 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003415 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3416 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003417 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003418 }
3419
3420 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3421 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003422 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003423 }
3424
3425 if (SynthesizePID) {
3426 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3427 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003428 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003429 }
3430
3431 // FIXME: OBJCGC: weak & strong
3432}
3433
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003434/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003435/// Another legacy compatibility encoding: 32-bit longs are encoded as
3436/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003437/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3438///
3439void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003440 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003441 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003442 if (BT->getKind() == BuiltinType::ULong &&
3443 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003444 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003445 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003446 if (BT->getKind() == BuiltinType::Long &&
3447 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003448 PointeeTy = IntTy;
3449 }
3450 }
3451}
3452
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003453void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003454 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003455 // We follow the behavior of gcc, expanding structures which are
3456 // directly pointed to, and expanding embedded structures. Note that
3457 // these rules are sufficient to prevent recursive encoding of the
3458 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003459 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003460 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003461}
3462
David Chisnall64fd7e82010-06-04 01:10:52 +00003463static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3464 switch (T->getAs<BuiltinType>()->getKind()) {
3465 default: assert(0 && "Unhandled builtin type kind");
3466 case BuiltinType::Void: return 'v';
3467 case BuiltinType::Bool: return 'B';
3468 case BuiltinType::Char_U:
3469 case BuiltinType::UChar: return 'C';
3470 case BuiltinType::UShort: return 'S';
3471 case BuiltinType::UInt: return 'I';
3472 case BuiltinType::ULong:
3473 return
3474 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3475 case BuiltinType::UInt128: return 'T';
3476 case BuiltinType::ULongLong: return 'Q';
3477 case BuiltinType::Char_S:
3478 case BuiltinType::SChar: return 'c';
3479 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003480 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003481 case BuiltinType::Int: return 'i';
3482 case BuiltinType::Long:
3483 return
3484 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3485 case BuiltinType::LongLong: return 'q';
3486 case BuiltinType::Int128: return 't';
3487 case BuiltinType::Float: return 'f';
3488 case BuiltinType::Double: return 'd';
3489 case BuiltinType::LongDouble: return 'd';
3490 }
3491}
3492
Mike Stump1eb44332009-09-09 15:08:12 +00003493static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003494 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003495 const Expr *E = FD->getBitWidth();
3496 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3497 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003498 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003499 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3500 // The GNU runtime requires more information; bitfields are encoded as b,
3501 // then the offset (in bits) of the first element, then the type of the
3502 // bitfield, then the size in bits. For example, in this structure:
3503 //
3504 // struct
3505 // {
3506 // int integer;
3507 // int flags:2;
3508 // };
3509 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3510 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3511 // information is not especially sensible, but we're stuck with it for
3512 // compatibility with GCC, although providing it breaks anything that
3513 // actually uses runtime introspection and wants to work on both runtimes...
3514 if (!Ctx->getLangOptions().NeXTRuntime) {
3515 const RecordDecl *RD = FD->getParent();
3516 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3517 // FIXME: This same linear search is also used in ExprConstant - it might
3518 // be better if the FieldDecl stored its offset. We'd be increasing the
3519 // size of the object slightly, but saving some time every time it is used.
3520 unsigned i = 0;
3521 for (RecordDecl::field_iterator Field = RD->field_begin(),
3522 FieldEnd = RD->field_end();
3523 Field != FieldEnd; (void)++Field, ++i) {
3524 if (*Field == FD)
3525 break;
3526 }
3527 S += llvm::utostr(RL.getFieldOffset(i));
3528 S += ObjCEncodingForPrimitiveKind(Context, T);
3529 }
3530 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003531 S += llvm::utostr(N);
3532}
3533
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003534// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003535void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3536 bool ExpandPointedToStructures,
3537 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003538 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003539 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003540 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003541 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003542 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003543 return EncodeBitField(this, S, T, FD);
3544 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003545 return;
3546 }
Mike Stump1eb44332009-09-09 15:08:12 +00003547
John McCall183700f2009-09-21 23:43:11 +00003548 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003549 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003550 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003551 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003552 return;
3553 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003554
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003555 // encoding for pointer or r3eference types.
3556 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003557 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003558 if (PT->isObjCSelType()) {
3559 S += ':';
3560 return;
3561 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003562 PointeeTy = PT->getPointeeType();
3563 }
3564 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3565 PointeeTy = RT->getPointeeType();
3566 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003567 bool isReadOnly = false;
3568 // For historical/compatibility reasons, the read-only qualifier of the
3569 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3570 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003571 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003572 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003573 if (OutermostType && T.isConstQualified()) {
3574 isReadOnly = true;
3575 S += 'r';
3576 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003577 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003578 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003579 while (P->getAs<PointerType>())
3580 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003581 if (P.isConstQualified()) {
3582 isReadOnly = true;
3583 S += 'r';
3584 }
3585 }
3586 if (isReadOnly) {
3587 // Another legacy compatibility encoding. Some ObjC qualifier and type
3588 // combinations need to be rearranged.
3589 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003590 if (llvm::StringRef(S).endswith("nr"))
3591 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003592 }
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003594 if (PointeeTy->isCharType()) {
3595 // char pointer types should be encoded as '*' unless it is a
3596 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003597 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003598 S += '*';
3599 return;
3600 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003601 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003602 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3603 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3604 S += '#';
3605 return;
3606 }
3607 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3608 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3609 S += '@';
3610 return;
3611 }
3612 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003613 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003614 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003615 getLegacyIntegralTypeEncoding(PointeeTy);
3616
Mike Stump1eb44332009-09-09 15:08:12 +00003617 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003618 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003619 return;
3620 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003621
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003622 if (const ArrayType *AT =
3623 // Ignore type qualifiers etc.
3624 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003625 if (isa<IncompleteArrayType>(AT)) {
3626 // Incomplete arrays are encoded as a pointer to the array element.
3627 S += '^';
3628
Mike Stump1eb44332009-09-09 15:08:12 +00003629 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003630 false, ExpandStructures, FD);
3631 } else {
3632 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Anders Carlsson559a8332009-02-22 01:38:57 +00003634 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3635 S += llvm::utostr(CAT->getSize().getZExtValue());
3636 else {
3637 //Variable length arrays are encoded as a regular array with 0 elements.
3638 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3639 S += '0';
3640 }
Mike Stump1eb44332009-09-09 15:08:12 +00003641
3642 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003643 false, ExpandStructures, FD);
3644 S += ']';
3645 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003646 return;
3647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
John McCall183700f2009-09-21 23:43:11 +00003649 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003650 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003651 return;
3652 }
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Ted Kremenek6217b802009-07-29 21:53:49 +00003654 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003655 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003656 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003657 // Anonymous structures print as '?'
3658 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3659 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003660 if (ClassTemplateSpecializationDecl *Spec
3661 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3662 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3663 std::string TemplateArgsStr
3664 = TemplateSpecializationType::PrintTemplateArgumentList(
3665 TemplateArgs.getFlatArgumentList(),
3666 TemplateArgs.flat_size(),
3667 (*this).PrintingPolicy);
3668
3669 S += TemplateArgsStr;
3670 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003671 } else {
3672 S += '?';
3673 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003674 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003675 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003676 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3677 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003678 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003679 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003680 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003681 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003682 S += '"';
3683 }
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003685 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003686 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003687 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003688 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003689 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003690 QualType qt = Field->getType();
3691 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003692 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003693 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003694 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003695 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003696 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003697 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003698 return;
3699 }
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003701 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003702 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003703 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003704 else
3705 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003706 return;
3707 }
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003709 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003710 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003711 return;
3712 }
Mike Stump1eb44332009-09-09 15:08:12 +00003713
John McCallc12c5bb2010-05-15 11:32:37 +00003714 // Ignore protocol qualifiers when mangling at this level.
3715 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3716 T = OT->getBaseType();
3717
John McCall0953e762009-09-24 19:53:00 +00003718 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003719 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003720 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003721 S += '{';
3722 const IdentifierInfo *II = OI->getIdentifier();
3723 S += II->getName();
3724 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003725 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003726 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003727 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003728 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003729 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003730 RecFields[i]);
3731 else
Mike Stump1eb44332009-09-09 15:08:12 +00003732 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003733 FD);
3734 }
3735 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003736 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003737 }
Mike Stump1eb44332009-09-09 15:08:12 +00003738
John McCall183700f2009-09-21 23:43:11 +00003739 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003740 if (OPT->isObjCIdType()) {
3741 S += '@';
3742 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003743 }
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Steve Naroff27d20a22009-10-28 22:03:49 +00003745 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3746 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3747 // Since this is a binary compatibility issue, need to consult with runtime
3748 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003749 S += '#';
3750 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003751 }
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003753 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003754 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003755 ExpandPointedToStructures,
3756 ExpandStructures, FD);
3757 if (FD || EncodingProperty) {
3758 // Note that we do extended encoding of protocol qualifer list
3759 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003760 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003761 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3762 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003763 S += '<';
3764 S += (*I)->getNameAsString();
3765 S += '>';
3766 }
3767 S += '"';
3768 }
3769 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003770 }
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003772 QualType PointeeTy = OPT->getPointeeType();
3773 if (!EncodingProperty &&
3774 isa<TypedefType>(PointeeTy.getTypePtr())) {
3775 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003776 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003777 // {...};
3778 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003779 getObjCEncodingForTypeImpl(PointeeTy, S,
3780 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003781 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003782 return;
3783 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003784
3785 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003786 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003787 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003788 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003789 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3790 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003791 S += '<';
3792 S += (*I)->getNameAsString();
3793 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003794 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003795 S += '"';
3796 }
3797 return;
3798 }
Mike Stump1eb44332009-09-09 15:08:12 +00003799
John McCall532ec7b2010-05-17 23:56:34 +00003800 // gcc just blithely ignores member pointers.
3801 // TODO: maybe there should be a mangling for these
3802 if (T->getAs<MemberPointerType>())
3803 return;
3804
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003805 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003806}
3807
Mike Stump1eb44332009-09-09 15:08:12 +00003808void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003809 std::string& S) const {
3810 if (QT & Decl::OBJC_TQ_In)
3811 S += 'n';
3812 if (QT & Decl::OBJC_TQ_Inout)
3813 S += 'N';
3814 if (QT & Decl::OBJC_TQ_Out)
3815 S += 'o';
3816 if (QT & Decl::OBJC_TQ_Bycopy)
3817 S += 'O';
3818 if (QT & Decl::OBJC_TQ_Byref)
3819 S += 'R';
3820 if (QT & Decl::OBJC_TQ_Oneway)
3821 S += 'V';
3822}
3823
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003824void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003825 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003826
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003827 BuiltinVaListType = T;
3828}
3829
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003830void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003831 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003832}
3833
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003834void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003835 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003836}
3837
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003838void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003839 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003840}
3841
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003842void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003843 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003844}
3845
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003846void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003847 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003848 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003850 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003851}
3852
John McCall0bd6feb2009-12-02 08:04:21 +00003853/// \brief Retrieve the template name that corresponds to a non-empty
3854/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003855TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3856 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003857 unsigned size = End - Begin;
3858 assert(size > 1 && "set is not overloaded!");
3859
3860 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3861 size * sizeof(FunctionTemplateDecl*));
3862 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3863
3864 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003865 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003866 NamedDecl *D = *I;
3867 assert(isa<FunctionTemplateDecl>(D) ||
3868 (isa<UsingShadowDecl>(D) &&
3869 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3870 *Storage++ = D;
3871 }
3872
3873 return TemplateName(OT);
3874}
3875
Douglas Gregor7532dc62009-03-30 22:58:21 +00003876/// \brief Retrieve the template name that represents a qualified
3877/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003878TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003879 bool TemplateKeyword,
3880 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003881 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003882 llvm::FoldingSetNodeID ID;
3883 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3884
3885 void *InsertPos = 0;
3886 QualifiedTemplateName *QTN =
3887 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3888 if (!QTN) {
3889 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3890 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3891 }
3892
3893 return TemplateName(QTN);
3894}
3895
3896/// \brief Retrieve the template name that represents a dependent
3897/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003898TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003899 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003900 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003901 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003902
3903 llvm::FoldingSetNodeID ID;
3904 DependentTemplateName::Profile(ID, NNS, Name);
3905
3906 void *InsertPos = 0;
3907 DependentTemplateName *QTN =
3908 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3909
3910 if (QTN)
3911 return TemplateName(QTN);
3912
3913 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3914 if (CanonNNS == NNS) {
3915 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3916 } else {
3917 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3918 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003919 DependentTemplateName *CheckQTN =
3920 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3921 assert(!CheckQTN && "Dependent type name canonicalization broken");
3922 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003923 }
3924
3925 DependentTemplateNames.InsertNode(QTN, InsertPos);
3926 return TemplateName(QTN);
3927}
3928
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003929/// \brief Retrieve the template name that represents a dependent
3930/// template name such as \c MetaFun::template operator+.
3931TemplateName
3932ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3933 OverloadedOperatorKind Operator) {
3934 assert((!NNS || NNS->isDependent()) &&
3935 "Nested name specifier must be dependent");
3936
3937 llvm::FoldingSetNodeID ID;
3938 DependentTemplateName::Profile(ID, NNS, Operator);
3939
3940 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003941 DependentTemplateName *QTN
3942 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003943
3944 if (QTN)
3945 return TemplateName(QTN);
3946
3947 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3948 if (CanonNNS == NNS) {
3949 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3950 } else {
3951 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3952 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003953
3954 DependentTemplateName *CheckQTN
3955 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3956 assert(!CheckQTN && "Dependent template name canonicalization broken");
3957 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003958 }
3959
3960 DependentTemplateNames.InsertNode(QTN, InsertPos);
3961 return TemplateName(QTN);
3962}
3963
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003964/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003965/// TargetInfo, produce the corresponding type. The unsigned @p Type
3966/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003967CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003968 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003969 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003970 case TargetInfo::SignedShort: return ShortTy;
3971 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3972 case TargetInfo::SignedInt: return IntTy;
3973 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3974 case TargetInfo::SignedLong: return LongTy;
3975 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3976 case TargetInfo::SignedLongLong: return LongLongTy;
3977 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3978 }
3979
3980 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003981 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003982}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003983
3984//===----------------------------------------------------------------------===//
3985// Type Predicates.
3986//===----------------------------------------------------------------------===//
3987
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003988/// isObjCNSObjectType - Return true if this is an NSObject object using
3989/// NSObject attribute on a c-style pointer type.
3990/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003991/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003992///
3993bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3994 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3995 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003996 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003997 return true;
3998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004000}
4001
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004002/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4003/// garbage collection attribute.
4004///
John McCall0953e762009-09-24 19:53:00 +00004005Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4006 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004007 if (getLangOptions().ObjC1 &&
4008 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004009 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004010 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004011 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004012 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004013 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004014 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004015 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004016 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004017 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004018 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004019 // Non-pointers have none gc'able attribute regardless of the attribute
4020 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004021 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004022 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004023 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004024 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004025}
4026
Chris Lattner6ac46a42008-04-07 06:51:04 +00004027//===----------------------------------------------------------------------===//
4028// Type Compatibility Testing
4029//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004030
Mike Stump1eb44332009-09-09 15:08:12 +00004031/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004032/// compatible.
4033static bool areCompatVectorTypes(const VectorType *LHS,
4034 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004035 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004036 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004037 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004038}
4039
Steve Naroff4084c302009-07-23 01:01:38 +00004040//===----------------------------------------------------------------------===//
4041// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4042//===----------------------------------------------------------------------===//
4043
4044/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4045/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004046bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4047 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004048 if (lProto == rProto)
4049 return true;
4050 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4051 E = rProto->protocol_end(); PI != E; ++PI)
4052 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4053 return true;
4054 return false;
4055}
4056
Steve Naroff4084c302009-07-23 01:01:38 +00004057/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4058/// return true if lhs's protocols conform to rhs's protocol; false
4059/// otherwise.
4060bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4061 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4062 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4063 return false;
4064}
4065
4066/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4067/// ObjCQualifiedIDType.
4068bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4069 bool compare) {
4070 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004071 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004072 lhs->isObjCIdType() || lhs->isObjCClassType())
4073 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004074 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004075 rhs->isObjCIdType() || rhs->isObjCClassType())
4076 return true;
4077
4078 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004079 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Steve Naroff4084c302009-07-23 01:01:38 +00004081 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004082
Steve Naroff4084c302009-07-23 01:01:38 +00004083 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004084 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004085 // make sure we check the class hierarchy.
4086 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4087 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4088 E = lhsQID->qual_end(); I != E; ++I) {
4089 // when comparing an id<P> on lhs with a static type on rhs,
4090 // see if static class implements all of id's protocols, directly or
4091 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004092 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004093 return false;
4094 }
4095 }
4096 // If there are no qualifiers and no interface, we have an 'id'.
4097 return true;
4098 }
Mike Stump1eb44332009-09-09 15:08:12 +00004099 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004100 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4101 E = lhsQID->qual_end(); I != E; ++I) {
4102 ObjCProtocolDecl *lhsProto = *I;
4103 bool match = false;
4104
4105 // when comparing an id<P> on lhs with a static type on rhs,
4106 // see if static class implements all of id's protocols, directly or
4107 // through its super class and categories.
4108 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4109 E = rhsOPT->qual_end(); J != E; ++J) {
4110 ObjCProtocolDecl *rhsProto = *J;
4111 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4112 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4113 match = true;
4114 break;
4115 }
4116 }
Mike Stump1eb44332009-09-09 15:08:12 +00004117 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004118 // make sure we check the class hierarchy.
4119 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4120 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4121 E = lhsQID->qual_end(); I != E; ++I) {
4122 // when comparing an id<P> on lhs with a static type on rhs,
4123 // see if static class implements all of id's protocols, directly or
4124 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004125 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004126 match = true;
4127 break;
4128 }
4129 }
4130 }
4131 if (!match)
4132 return false;
4133 }
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Steve Naroff4084c302009-07-23 01:01:38 +00004135 return true;
4136 }
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Steve Naroff4084c302009-07-23 01:01:38 +00004138 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4139 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4140
Mike Stump1eb44332009-09-09 15:08:12 +00004141 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004142 lhs->getAsObjCInterfacePointerType()) {
4143 if (lhsOPT->qual_empty()) {
4144 bool match = false;
4145 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4146 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4147 E = rhsQID->qual_end(); I != E; ++I) {
4148 // when comparing an id<P> on lhs with a static type on rhs,
4149 // see if static class implements all of id's protocols, directly or
4150 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004151 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004152 match = true;
4153 break;
4154 }
4155 }
4156 if (!match)
4157 return false;
4158 }
4159 return true;
4160 }
Mike Stump1eb44332009-09-09 15:08:12 +00004161 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004162 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4163 E = lhsOPT->qual_end(); I != E; ++I) {
4164 ObjCProtocolDecl *lhsProto = *I;
4165 bool match = false;
4166
4167 // when comparing an id<P> on lhs with a static type on rhs,
4168 // see if static class implements all of id's protocols, directly or
4169 // through its super class and categories.
4170 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4171 E = rhsQID->qual_end(); J != E; ++J) {
4172 ObjCProtocolDecl *rhsProto = *J;
4173 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4174 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4175 match = true;
4176 break;
4177 }
4178 }
4179 if (!match)
4180 return false;
4181 }
4182 return true;
4183 }
4184 return false;
4185}
4186
Eli Friedman3d815e72008-08-22 00:56:42 +00004187/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004188/// compatible for assignment from RHS to LHS. This handles validation of any
4189/// protocol qualifiers on the LHS or RHS.
4190///
Steve Naroff14108da2009-07-10 23:34:53 +00004191bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4192 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004193 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4194 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4195
Steve Naroffde2e22d2009-07-15 18:40:39 +00004196 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004197 if (LHS->isObjCUnqualifiedIdOrClass() ||
4198 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004199 return true;
4200
John McCallc12c5bb2010-05-15 11:32:37 +00004201 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004202 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4203 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004204 false);
4205
John McCallc12c5bb2010-05-15 11:32:37 +00004206 // If we have 2 user-defined types, fall into that path.
4207 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004208 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004209
Steve Naroff4084c302009-07-23 01:01:38 +00004210 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004211}
4212
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004213/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4214/// for providing type-safty for objective-c pointers used to pass/return
4215/// arguments in block literals. When passed as arguments, passing 'A*' where
4216/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4217/// not OK. For the return type, the opposite is not OK.
4218bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4219 const ObjCObjectPointerType *LHSOPT,
4220 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004221 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004222 return true;
4223
4224 if (LHSOPT->isObjCBuiltinType()) {
4225 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4226 }
4227
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004228 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004229 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4230 QualType(RHSOPT,0),
4231 false);
4232
4233 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4234 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4235 if (LHS && RHS) { // We have 2 user-defined types.
4236 if (LHS != RHS) {
4237 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4238 return false;
4239 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4240 return true;
4241 }
4242 else
4243 return true;
4244 }
4245 return false;
4246}
4247
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004248/// getIntersectionOfProtocols - This routine finds the intersection of set
4249/// of protocols inherited from two distinct objective-c pointer objects.
4250/// It is used to build composite qualifier list of the composite type of
4251/// the conditional expression involving two objective-c pointer objects.
4252static
4253void getIntersectionOfProtocols(ASTContext &Context,
4254 const ObjCObjectPointerType *LHSOPT,
4255 const ObjCObjectPointerType *RHSOPT,
4256 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4257
John McCallc12c5bb2010-05-15 11:32:37 +00004258 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4259 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4260 assert(LHS->getInterface() && "LHS must have an interface base");
4261 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004262
4263 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4264 unsigned LHSNumProtocols = LHS->getNumProtocols();
4265 if (LHSNumProtocols > 0)
4266 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4267 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004268 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004269 Context.CollectInheritedProtocols(LHS->getInterface(),
4270 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004271 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4272 LHSInheritedProtocols.end());
4273 }
4274
4275 unsigned RHSNumProtocols = RHS->getNumProtocols();
4276 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004277 ObjCProtocolDecl **RHSProtocols =
4278 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004279 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4280 if (InheritedProtocolSet.count(RHSProtocols[i]))
4281 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4282 }
4283 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004284 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004285 Context.CollectInheritedProtocols(RHS->getInterface(),
4286 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004287 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4288 RHSInheritedProtocols.begin(),
4289 E = RHSInheritedProtocols.end(); I != E; ++I)
4290 if (InheritedProtocolSet.count((*I)))
4291 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004292 }
4293}
4294
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004295/// areCommonBaseCompatible - Returns common base class of the two classes if
4296/// one found. Note that this is O'2 algorithm. But it will be called as the
4297/// last type comparison in a ?-exp of ObjC pointer types before a
4298/// warning is issued. So, its invokation is extremely rare.
4299QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004300 const ObjCObjectPointerType *Lptr,
4301 const ObjCObjectPointerType *Rptr) {
4302 const ObjCObjectType *LHS = Lptr->getObjectType();
4303 const ObjCObjectType *RHS = Rptr->getObjectType();
4304 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4305 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4306 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004307 return QualType();
4308
John McCallc12c5bb2010-05-15 11:32:37 +00004309 while ((LDecl = LDecl->getSuperClass())) {
4310 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004311 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004312 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4313 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4314
4315 QualType Result = QualType(LHS, 0);
4316 if (!Protocols.empty())
4317 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4318 Result = getObjCObjectPointerType(Result);
4319 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004320 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004321 }
4322
4323 return QualType();
4324}
4325
John McCallc12c5bb2010-05-15 11:32:37 +00004326bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4327 const ObjCObjectType *RHS) {
4328 assert(LHS->getInterface() && "LHS is not an interface type");
4329 assert(RHS->getInterface() && "RHS is not an interface type");
4330
Chris Lattner6ac46a42008-04-07 06:51:04 +00004331 // Verify that the base decls are compatible: the RHS must be a subclass of
4332 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004333 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Chris Lattner6ac46a42008-04-07 06:51:04 +00004336 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4337 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004338 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004339 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004340
Chris Lattner6ac46a42008-04-07 06:51:04 +00004341 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4342 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004343 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004344 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004345
John McCallc12c5bb2010-05-15 11:32:37 +00004346 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4347 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004348 LHSPI != LHSPE; LHSPI++) {
4349 bool RHSImplementsProtocol = false;
4350
4351 // If the RHS doesn't implement the protocol on the left, the types
4352 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004353 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4354 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004355 RHSPI != RHSPE; RHSPI++) {
4356 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004357 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004358 break;
4359 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004360 }
4361 // FIXME: For better diagnostics, consider passing back the protocol name.
4362 if (!RHSImplementsProtocol)
4363 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004364 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004365 // The RHS implements all protocols listed on the LHS.
4366 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004367}
4368
Steve Naroff389bf462009-02-12 17:52:19 +00004369bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4370 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004371 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4372 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004373
Steve Naroff14108da2009-07-10 23:34:53 +00004374 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004375 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004376
4377 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4378 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004379}
4380
Mike Stump1eb44332009-09-09 15:08:12 +00004381/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004382/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004383/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004384/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004385bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004386 if (getLangOptions().CPlusPlus)
4387 return hasSameType(LHS, RHS);
4388
Eli Friedman3d815e72008-08-22 00:56:42 +00004389 return !mergeTypes(LHS, RHS).isNull();
4390}
4391
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004392bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4393 return !mergeTypes(LHS, RHS, true).isNull();
4394}
4395
4396QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4397 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004398 const FunctionType *lbase = lhs->getAs<FunctionType>();
4399 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004400 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4401 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004402 bool allLTypes = true;
4403 bool allRTypes = true;
4404
4405 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004406 QualType retType;
4407 if (OfBlockPointer)
4408 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4409 else
4410 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004411 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004412 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004413 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004414 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004415 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004416 // FIXME: double check this
4417 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4418 // rbase->getRegParmAttr() != 0 &&
4419 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004420 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4421 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004422 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4423 lbaseInfo.getRegParm();
4424 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4425 if (NoReturn != lbaseInfo.getNoReturn() ||
4426 RegParm != lbaseInfo.getRegParm())
4427 allLTypes = false;
4428 if (NoReturn != rbaseInfo.getNoReturn() ||
4429 RegParm != rbaseInfo.getRegParm())
4430 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004431 CallingConv lcc = lbaseInfo.getCC();
4432 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004433 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004434 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004435 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Eli Friedman3d815e72008-08-22 00:56:42 +00004437 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004438 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4439 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004440 unsigned lproto_nargs = lproto->getNumArgs();
4441 unsigned rproto_nargs = rproto->getNumArgs();
4442
4443 // Compatible functions must have the same number of arguments
4444 if (lproto_nargs != rproto_nargs)
4445 return QualType();
4446
4447 // Variadic and non-variadic functions aren't compatible
4448 if (lproto->isVariadic() != rproto->isVariadic())
4449 return QualType();
4450
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004451 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4452 return QualType();
4453
Eli Friedman3d815e72008-08-22 00:56:42 +00004454 // Check argument compatibility
4455 llvm::SmallVector<QualType, 10> types;
4456 for (unsigned i = 0; i < lproto_nargs; i++) {
4457 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4458 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004459 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004460 if (argtype.isNull()) return QualType();
4461 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004462 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4463 allLTypes = false;
4464 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4465 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004466 }
4467 if (allLTypes) return lhs;
4468 if (allRTypes) return rhs;
4469 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004470 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004471 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004472 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004473 }
4474
4475 if (lproto) allRTypes = false;
4476 if (rproto) allLTypes = false;
4477
Douglas Gregor72564e72009-02-26 23:50:07 +00004478 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004479 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004480 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004481 if (proto->isVariadic()) return QualType();
4482 // Check that the types are compatible with the types that
4483 // would result from default argument promotions (C99 6.7.5.3p15).
4484 // The only types actually affected are promotable integer
4485 // types and floats, which would be passed as a different
4486 // type depending on whether the prototype is visible.
4487 unsigned proto_nargs = proto->getNumArgs();
4488 for (unsigned i = 0; i < proto_nargs; ++i) {
4489 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004490
4491 // Look at the promotion type of enum types, since that is the type used
4492 // to pass enum values.
4493 if (const EnumType *Enum = argTy->getAs<EnumType>())
4494 argTy = Enum->getDecl()->getPromotionType();
4495
Eli Friedman3d815e72008-08-22 00:56:42 +00004496 if (argTy->isPromotableIntegerType() ||
4497 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4498 return QualType();
4499 }
4500
4501 if (allLTypes) return lhs;
4502 if (allRTypes) return rhs;
4503 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004504 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004505 proto->getTypeQuals(),
4506 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004507 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004508 }
4509
4510 if (allLTypes) return lhs;
4511 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004512 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004513 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004514}
4515
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004516QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4517 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004518 // C++ [expr]: If an expression initially has the type "reference to T", the
4519 // type is adjusted to "T" prior to any further analysis, the expression
4520 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004521 // expression is an lvalue unless the reference is an rvalue reference and
4522 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004523 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4524 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4525
Eli Friedman3d815e72008-08-22 00:56:42 +00004526 QualType LHSCan = getCanonicalType(LHS),
4527 RHSCan = getCanonicalType(RHS);
4528
4529 // If two types are identical, they are compatible.
4530 if (LHSCan == RHSCan)
4531 return LHS;
4532
John McCall0953e762009-09-24 19:53:00 +00004533 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004534 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4535 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004536 if (LQuals != RQuals) {
4537 // If any of these qualifiers are different, we have a type
4538 // mismatch.
4539 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4540 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4541 return QualType();
4542
4543 // Exactly one GC qualifier difference is allowed: __strong is
4544 // okay if the other type has no GC qualifier but is an Objective
4545 // C object pointer (i.e. implicitly strong by default). We fix
4546 // this by pretending that the unqualified type was actually
4547 // qualified __strong.
4548 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4549 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4550 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4551
4552 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4553 return QualType();
4554
4555 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4556 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4557 }
4558 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4559 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4560 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004561 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004562 }
4563
4564 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004565
Eli Friedman852d63b2009-06-01 01:22:52 +00004566 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4567 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004568
Chris Lattner1adb8832008-01-14 05:45:46 +00004569 // We want to consider the two function types to be the same for these
4570 // comparisons, just force one to the other.
4571 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4572 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004573
4574 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004575 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4576 LHSClass = Type::ConstantArray;
4577 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4578 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004579
John McCallc12c5bb2010-05-15 11:32:37 +00004580 // ObjCInterfaces are just specialized ObjCObjects.
4581 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4582 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4583
Nate Begeman213541a2008-04-18 23:10:10 +00004584 // Canonicalize ExtVector -> Vector.
4585 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4586 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Chris Lattnera36a61f2008-04-07 05:43:21 +00004588 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004589 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004590 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004591 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004592 // Compatibility is based on the underlying type, not the promotion
4593 // type.
John McCall183700f2009-09-21 23:43:11 +00004594 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004595 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4596 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004597 }
John McCall183700f2009-09-21 23:43:11 +00004598 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004599 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4600 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004601 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004602
Eli Friedman3d815e72008-08-22 00:56:42 +00004603 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004604 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004605
Steve Naroff4a746782008-01-09 22:43:08 +00004606 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004607 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004608#define TYPE(Class, Base)
4609#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004610#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004611#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4612#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4613#include "clang/AST/TypeNodes.def"
4614 assert(false && "Non-canonical and dependent types shouldn't get here");
4615 return QualType();
4616
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004617 case Type::LValueReference:
4618 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004619 case Type::MemberPointer:
4620 assert(false && "C++ should never be in mergeTypes");
4621 return QualType();
4622
John McCallc12c5bb2010-05-15 11:32:37 +00004623 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004624 case Type::IncompleteArray:
4625 case Type::VariableArray:
4626 case Type::FunctionProto:
4627 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004628 assert(false && "Types are eliminated above");
4629 return QualType();
4630
Chris Lattner1adb8832008-01-14 05:45:46 +00004631 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004632 {
4633 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004634 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4635 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004636 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4637 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004638 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004639 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004640 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004641 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004642 return getPointerType(ResultType);
4643 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004644 case Type::BlockPointer:
4645 {
4646 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004647 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4648 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004649 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004650 if (ResultType.isNull()) return QualType();
4651 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4652 return LHS;
4653 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4654 return RHS;
4655 return getBlockPointerType(ResultType);
4656 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004657 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004658 {
4659 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4660 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4661 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4662 return QualType();
4663
4664 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4665 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4666 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4667 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004668 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4669 return LHS;
4670 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4671 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004672 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4673 ArrayType::ArraySizeModifier(), 0);
4674 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4675 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004676 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4677 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004678 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4679 return LHS;
4680 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4681 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004682 if (LVAT) {
4683 // FIXME: This isn't correct! But tricky to implement because
4684 // the array's size has to be the size of LHS, but the type
4685 // has to be different.
4686 return LHS;
4687 }
4688 if (RVAT) {
4689 // FIXME: This isn't correct! But tricky to implement because
4690 // the array's size has to be the size of RHS, but the type
4691 // has to be different.
4692 return RHS;
4693 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004694 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4695 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004696 return getIncompleteArrayType(ResultType,
4697 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004698 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004699 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004700 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004701 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004702 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004703 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004704 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004705 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004706 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004707 case Type::Complex:
4708 // Distinct complex types are incompatible.
4709 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004710 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004711 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004712 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4713 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004714 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004715 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004716 case Type::ObjCObject: {
4717 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004718 // FIXME: This should be type compatibility, e.g. whether
4719 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004720 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4721 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4722 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004723 return LHS;
4724
Eli Friedman3d815e72008-08-22 00:56:42 +00004725 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004726 }
Steve Naroff14108da2009-07-10 23:34:53 +00004727 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004728 if (OfBlockPointer) {
4729 if (canAssignObjCInterfacesInBlockPointer(
4730 LHS->getAs<ObjCObjectPointerType>(),
4731 RHS->getAs<ObjCObjectPointerType>()))
4732 return LHS;
4733 return QualType();
4734 }
John McCall183700f2009-09-21 23:43:11 +00004735 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4736 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004737 return LHS;
4738
Steve Naroffbc76dd02008-12-10 22:14:21 +00004739 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004740 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004741 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004742
4743 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004744}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004745
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004746/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4747/// 'RHS' attributes and returns the merged version; including for function
4748/// return types.
4749QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4750 QualType LHSCan = getCanonicalType(LHS),
4751 RHSCan = getCanonicalType(RHS);
4752 // If two types are identical, they are compatible.
4753 if (LHSCan == RHSCan)
4754 return LHS;
4755 if (RHSCan->isFunctionType()) {
4756 if (!LHSCan->isFunctionType())
4757 return QualType();
4758 QualType OldReturnType =
4759 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4760 QualType NewReturnType =
4761 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4762 QualType ResReturnType =
4763 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4764 if (ResReturnType.isNull())
4765 return QualType();
4766 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4767 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4768 // In either case, use OldReturnType to build the new function type.
4769 const FunctionType *F = LHS->getAs<FunctionType>();
4770 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4771 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4772 QualType ResultType
4773 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4774 FPT->getNumArgs(), FPT->isVariadic(),
4775 FPT->getTypeQuals(),
4776 FPT->hasExceptionSpec(),
4777 FPT->hasAnyExceptionSpec(),
4778 FPT->getNumExceptions(),
4779 FPT->exception_begin(),
4780 Info);
4781 return ResultType;
4782 }
4783 }
4784 return QualType();
4785 }
4786
4787 // If the qualifiers are different, the types can still be merged.
4788 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4789 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4790 if (LQuals != RQuals) {
4791 // If any of these qualifiers are different, we have a type mismatch.
4792 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4793 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4794 return QualType();
4795
4796 // Exactly one GC qualifier difference is allowed: __strong is
4797 // okay if the other type has no GC qualifier but is an Objective
4798 // C object pointer (i.e. implicitly strong by default). We fix
4799 // this by pretending that the unqualified type was actually
4800 // qualified __strong.
4801 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4802 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4803 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4804
4805 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4806 return QualType();
4807
4808 if (GC_L == Qualifiers::Strong)
4809 return LHS;
4810 if (GC_R == Qualifiers::Strong)
4811 return RHS;
4812 return QualType();
4813 }
4814
4815 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4816 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4817 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4818 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4819 if (ResQT == LHSBaseQT)
4820 return LHS;
4821 if (ResQT == RHSBaseQT)
4822 return RHS;
4823 }
4824 return QualType();
4825}
4826
Chris Lattner5426bf62008-04-07 07:01:58 +00004827//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004828// Integer Predicates
4829//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004830
Eli Friedmanad74a752008-06-28 06:23:08 +00004831unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004832 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004833 return 1;
John McCall842aef82009-12-09 09:09:27 +00004834 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004835 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004836 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004837 return (unsigned)getTypeSize(T);
4838}
4839
4840QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4841 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004842
4843 // Turn <4 x signed int> -> <4 x unsigned int>
4844 if (const VectorType *VTy = T->getAs<VectorType>())
4845 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004846 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004847
4848 // For enums, we return the unsigned version of the base type.
4849 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004850 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004851
4852 const BuiltinType *BTy = T->getAs<BuiltinType>();
4853 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004854 switch (BTy->getKind()) {
4855 case BuiltinType::Char_S:
4856 case BuiltinType::SChar:
4857 return UnsignedCharTy;
4858 case BuiltinType::Short:
4859 return UnsignedShortTy;
4860 case BuiltinType::Int:
4861 return UnsignedIntTy;
4862 case BuiltinType::Long:
4863 return UnsignedLongTy;
4864 case BuiltinType::LongLong:
4865 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004866 case BuiltinType::Int128:
4867 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004868 default:
4869 assert(0 && "Unexpected signed integer type");
4870 return QualType();
4871 }
4872}
4873
Douglas Gregor2cf26342009-04-09 22:27:44 +00004874ExternalASTSource::~ExternalASTSource() { }
4875
4876void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004877
4878
4879//===----------------------------------------------------------------------===//
4880// Builtin Type Computation
4881//===----------------------------------------------------------------------===//
4882
4883/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4884/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004885static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004886 ASTContext::GetBuiltinTypeError &Error,
4887 bool AllowTypeModifiers = true) {
4888 // Modifiers.
4889 int HowLong = 0;
4890 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Chris Lattner86df27b2009-06-14 00:45:47 +00004892 // Read the modifiers first.
4893 bool Done = false;
4894 while (!Done) {
4895 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004896 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004897 case 'S':
4898 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4899 assert(!Signed && "Can't use 'S' modifier multiple times!");
4900 Signed = true;
4901 break;
4902 case 'U':
4903 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4904 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4905 Unsigned = true;
4906 break;
4907 case 'L':
4908 assert(HowLong <= 2 && "Can't have LLLL modifier");
4909 ++HowLong;
4910 break;
4911 }
4912 }
4913
4914 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Chris Lattner86df27b2009-06-14 00:45:47 +00004916 // Read the base type.
4917 switch (*Str++) {
4918 default: assert(0 && "Unknown builtin type letter!");
4919 case 'v':
4920 assert(HowLong == 0 && !Signed && !Unsigned &&
4921 "Bad modifiers used with 'v'!");
4922 Type = Context.VoidTy;
4923 break;
4924 case 'f':
4925 assert(HowLong == 0 && !Signed && !Unsigned &&
4926 "Bad modifiers used with 'f'!");
4927 Type = Context.FloatTy;
4928 break;
4929 case 'd':
4930 assert(HowLong < 2 && !Signed && !Unsigned &&
4931 "Bad modifiers used with 'd'!");
4932 if (HowLong)
4933 Type = Context.LongDoubleTy;
4934 else
4935 Type = Context.DoubleTy;
4936 break;
4937 case 's':
4938 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4939 if (Unsigned)
4940 Type = Context.UnsignedShortTy;
4941 else
4942 Type = Context.ShortTy;
4943 break;
4944 case 'i':
4945 if (HowLong == 3)
4946 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4947 else if (HowLong == 2)
4948 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4949 else if (HowLong == 1)
4950 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4951 else
4952 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4953 break;
4954 case 'c':
4955 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4956 if (Signed)
4957 Type = Context.SignedCharTy;
4958 else if (Unsigned)
4959 Type = Context.UnsignedCharTy;
4960 else
4961 Type = Context.CharTy;
4962 break;
4963 case 'b': // boolean
4964 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4965 Type = Context.BoolTy;
4966 break;
4967 case 'z': // size_t.
4968 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4969 Type = Context.getSizeType();
4970 break;
4971 case 'F':
4972 Type = Context.getCFConstantStringType();
4973 break;
4974 case 'a':
4975 Type = Context.getBuiltinVaListType();
4976 assert(!Type.isNull() && "builtin va list type not initialized!");
4977 break;
4978 case 'A':
4979 // This is a "reference" to a va_list; however, what exactly
4980 // this means depends on how va_list is defined. There are two
4981 // different kinds of va_list: ones passed by value, and ones
4982 // passed by reference. An example of a by-value va_list is
4983 // x86, where va_list is a char*. An example of by-ref va_list
4984 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4985 // we want this argument to be a char*&; for x86-64, we want
4986 // it to be a __va_list_tag*.
4987 Type = Context.getBuiltinVaListType();
4988 assert(!Type.isNull() && "builtin va list type not initialized!");
4989 if (Type->isArrayType()) {
4990 Type = Context.getArrayDecayedType(Type);
4991 } else {
4992 Type = Context.getLValueReferenceType(Type);
4993 }
4994 break;
4995 case 'V': {
4996 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004997 unsigned NumElements = strtoul(Str, &End, 10);
4998 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004999
Chris Lattner86df27b2009-06-14 00:45:47 +00005000 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005001
Chris Lattner86df27b2009-06-14 00:45:47 +00005002 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005003 // FIXME: Don't know what to do about AltiVec.
5004 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00005005 break;
5006 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005007 case 'X': {
5008 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5009 Type = Context.getComplexType(ElementType);
5010 break;
5011 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005012 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005013 Type = Context.getFILEType();
5014 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005015 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005016 return QualType();
5017 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005018 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005019 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005020 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005021 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005022 else
5023 Type = Context.getjmp_bufType();
5024
Mike Stumpfd612db2009-07-28 23:47:15 +00005025 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005026 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005027 return QualType();
5028 }
5029 break;
Mike Stump782fa302009-07-28 02:25:19 +00005030 }
Mike Stump1eb44332009-09-09 15:08:12 +00005031
Chris Lattner86df27b2009-06-14 00:45:47 +00005032 if (!AllowTypeModifiers)
5033 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005034
Chris Lattner86df27b2009-06-14 00:45:47 +00005035 Done = false;
5036 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005037 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005038 default: Done = true; --Str; break;
5039 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005040 case '&':
John McCall187ab372010-03-12 04:21:28 +00005041 {
5042 // Both pointers and references can have their pointee types
5043 // qualified with an address space.
5044 char *End;
5045 unsigned AddrSpace = strtoul(Str, &End, 10);
5046 if (End != Str && AddrSpace != 0) {
5047 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5048 Str = End;
5049 }
5050 }
5051 if (c == '*')
5052 Type = Context.getPointerType(Type);
5053 else
5054 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005055 break;
5056 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5057 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005058 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005059 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005060 case 'D':
5061 Type = Context.getVolatileType(Type);
5062 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005063 }
5064 }
Mike Stump1eb44332009-09-09 15:08:12 +00005065
Chris Lattner86df27b2009-06-14 00:45:47 +00005066 return Type;
5067}
5068
5069/// GetBuiltinType - Return the type for the specified builtin.
5070QualType ASTContext::GetBuiltinType(unsigned id,
5071 GetBuiltinTypeError &Error) {
5072 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005073
Chris Lattner86df27b2009-06-14 00:45:47 +00005074 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Chris Lattner86df27b2009-06-14 00:45:47 +00005076 Error = GE_None;
5077 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5078 if (Error != GE_None)
5079 return QualType();
5080 while (TypeStr[0] && TypeStr[0] != '.') {
5081 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5082 if (Error != GE_None)
5083 return QualType();
5084
5085 // Do array -> pointer decay. The builtin should use the decayed type.
5086 if (Ty->isArrayType())
5087 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005088
Chris Lattner86df27b2009-06-14 00:45:47 +00005089 ArgTypes.push_back(Ty);
5090 }
5091
5092 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5093 "'.' should only occur at end of builtin type list!");
5094
5095 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5096 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5097 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005098
5099 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005100 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005101 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005102 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005103}
Eli Friedmana95d7572009-08-19 07:44:53 +00005104
5105QualType
5106ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5107 // Perform the usual unary conversions. We do this early so that
5108 // integral promotions to "int" can allow us to exit early, in the
5109 // lhs == rhs check. Also, for conversion purposes, we ignore any
5110 // qualifiers. For example, "const float" and "float" are
5111 // equivalent.
5112 if (lhs->isPromotableIntegerType())
5113 lhs = getPromotedIntegerType(lhs);
5114 else
5115 lhs = lhs.getUnqualifiedType();
5116 if (rhs->isPromotableIntegerType())
5117 rhs = getPromotedIntegerType(rhs);
5118 else
5119 rhs = rhs.getUnqualifiedType();
5120
5121 // If both types are identical, no conversion is needed.
5122 if (lhs == rhs)
5123 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005124
Eli Friedmana95d7572009-08-19 07:44:53 +00005125 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5126 // The caller can deal with this (e.g. pointer + int).
5127 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5128 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005129
5130 // At this point, we have two different arithmetic types.
5131
Eli Friedmana95d7572009-08-19 07:44:53 +00005132 // Handle complex types first (C99 6.3.1.8p1).
5133 if (lhs->isComplexType() || rhs->isComplexType()) {
5134 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005135 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005136 // convert the rhs to the lhs complex type.
5137 return lhs;
5138 }
Mike Stump1eb44332009-09-09 15:08:12 +00005139 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005140 // convert the lhs to the rhs complex type.
5141 return rhs;
5142 }
5143 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005144 // When both operands are complex, the shorter operand is converted to the
5145 // type of the longer, and that is the type of the result. This corresponds
5146 // to what is done when combining two real floating-point operands.
5147 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005148 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005149 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005150 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005151 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005152 // "double _Complex" is promoted to "long double _Complex".
5153 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005154
5155 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005156 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005157 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005158 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005159 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005160 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5161 // domains match. This is a requirement for our implementation, C99
5162 // does not require this promotion.
5163 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5164 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5165 return rhs;
5166 } else { // handle "_Complex double, double".
5167 return lhs;
5168 }
5169 }
5170 return lhs; // The domain/size match exactly.
5171 }
5172 // Now handle "real" floating types (i.e. float, double, long double).
5173 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5174 // if we have an integer operand, the result is the real floating type.
5175 if (rhs->isIntegerType()) {
5176 // convert rhs to the lhs floating point type.
5177 return lhs;
5178 }
5179 if (rhs->isComplexIntegerType()) {
5180 // convert rhs to the complex floating point type.
5181 return getComplexType(lhs);
5182 }
5183 if (lhs->isIntegerType()) {
5184 // convert lhs to the rhs floating point type.
5185 return rhs;
5186 }
Mike Stump1eb44332009-09-09 15:08:12 +00005187 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005188 // convert lhs to the complex floating point type.
5189 return getComplexType(rhs);
5190 }
5191 // We have two real floating types, float/complex combos were handled above.
5192 // Convert the smaller operand to the bigger result.
5193 int result = getFloatingTypeOrder(lhs, rhs);
5194 if (result > 0) // convert the rhs
5195 return lhs;
5196 assert(result < 0 && "illegal float comparison");
5197 return rhs; // convert the lhs
5198 }
5199 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5200 // Handle GCC complex int extension.
5201 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5202 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5203
5204 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005205 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005206 rhsComplexInt->getElementType()) >= 0)
5207 return lhs; // convert the rhs
5208 return rhs;
5209 } else if (lhsComplexInt && rhs->isIntegerType()) {
5210 // convert the rhs to the lhs complex type.
5211 return lhs;
5212 } else if (rhsComplexInt && lhs->isIntegerType()) {
5213 // convert the lhs to the rhs complex type.
5214 return rhs;
5215 }
5216 }
5217 // Finally, we have two differing integer types.
5218 // The rules for this case are in C99 6.3.1.8
5219 int compare = getIntegerTypeOrder(lhs, rhs);
5220 bool lhsSigned = lhs->isSignedIntegerType(),
5221 rhsSigned = rhs->isSignedIntegerType();
5222 QualType destType;
5223 if (lhsSigned == rhsSigned) {
5224 // Same signedness; use the higher-ranked type
5225 destType = compare >= 0 ? lhs : rhs;
5226 } else if (compare != (lhsSigned ? 1 : -1)) {
5227 // The unsigned type has greater than or equal rank to the
5228 // signed type, so use the unsigned type
5229 destType = lhsSigned ? rhs : lhs;
5230 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5231 // The two types are different widths; if we are here, that
5232 // means the signed type is larger than the unsigned type, so
5233 // use the signed type.
5234 destType = lhsSigned ? lhs : rhs;
5235 } else {
5236 // The signed type is higher-ranked than the unsigned type,
5237 // but isn't actually any bigger (like unsigned int and long
5238 // on most 32-bit systems). Use the unsigned type corresponding
5239 // to the signed type.
5240 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5241 }
5242 return destType;
5243}