blob: fbf26ccca5ee402bb9eb3a0f0541b2be1d5285cc [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) :
John McCallef990012010-06-11 11:07:21 +000043 TemplateSpecializationTypes(this_()),
44 DependentTemplateSpecializationTypes(this_()),
Mike Stump1eb44332009-09-09 15:08:12 +000045 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +000046 NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000047 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000048 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +000049 NullTypeSourceInfo(QualType()),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +000050 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000051 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +000052 BuiltinInfo(builtins),
53 DeclarationNames(*this),
54 ExternalSource(0), PrintingPolicy(LOpts),
John McCall0c01d182010-03-24 05:22:00 +000055 LastSDM(0, 0) {
David Chisnall0f436562009-08-17 16:35:33 +000056 ObjCIdRedefinitionType = QualType();
57 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000058 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000059 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000060 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000061 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000062}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +000065 // Release the DenseMaps associated with DeclContext objects.
66 // FIXME: Is this the ideal solution?
67 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +000068
Douglas Gregor00545312010-05-23 18:26:36 +000069 if (!FreeMemory) {
70 // Call all of the deallocation functions.
71 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
72 Deallocations[I].first(Deallocations[I].second);
73 }
74
Douglas Gregor7d10b7e2010-03-02 23:58:15 +000075 // Release all of the memory associated with overridden C++ methods.
76 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
77 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
78 OM != OMEnd; ++OM)
79 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +000080
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000081 if (FreeMemory) {
82 // Deallocate all the types.
83 while (!Types.empty()) {
84 Types.back()->Destroy(*this);
85 Types.pop_back();
86 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000087
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000088 for (llvm::FoldingSet<ExtQuals>::iterator
89 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
90 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000091 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000092 }
Nuno Lopesb74668e2008-12-17 22:30:25 +000093
Ted Kremenek503524a2010-03-08 20:56:29 +000094 for (llvm::DenseMap<const ObjCContainerDecl*,
95 const ASTRecordLayout*>::iterator
96 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
97 // Increment in loop to prevent using deallocated memory.
98 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
99 R->Destroy(*this);
100 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000101 }
102
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000103 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
104 // even when using the BumpPtrAllocator because they can contain
105 // DenseMaps.
106 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
107 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
108 // Increment in loop to prevent using deallocated memory.
109 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
110 R->Destroy(*this);
111 }
112
Douglas Gregorab452ba2009-03-26 23:50:42 +0000113 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000114 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
115 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000116 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000117 NNS != NNSEnd; ) {
118 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000119 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000120 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000121
122 if (GlobalNestedNameSpecifier)
123 GlobalNestedNameSpecifier->Destroy(*this);
124
Eli Friedmanb26153c2008-05-27 03:08:09 +0000125 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000126}
127
Douglas Gregor00545312010-05-23 18:26:36 +0000128void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
129 Deallocations.push_back(std::make_pair(Callback, Data));
130}
131
Mike Stump1eb44332009-09-09 15:08:12 +0000132void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000133ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
134 ExternalSource.reset(Source.take());
135}
136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137void ASTContext::PrintStats() const {
138 fprintf(stderr, "*** AST Context Stats:\n");
139 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000140
Douglas Gregordbe833d2009-05-26 14:40:08 +0000141 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000142#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000143#define ABSTRACT_TYPE(Name, Parent)
144#include "clang/AST/TypeNodes.def"
145 0 // Extra
146 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000147
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
149 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000150 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 }
152
Douglas Gregordbe833d2009-05-26 14:40:08 +0000153 unsigned Idx = 0;
154 unsigned TotalBytes = 0;
155#define TYPE(Name, Parent) \
156 if (counts[Idx]) \
157 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
158 TotalBytes += counts[Idx] * sizeof(Name##Type); \
159 ++Idx;
160#define ABSTRACT_TYPE(Name, Parent)
161#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Douglas Gregordbe833d2009-05-26 14:40:08 +0000163 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000164
165 if (ExternalSource.get()) {
166 fprintf(stderr, "\n");
167 ExternalSource->PrintStats();
168 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000169}
170
171
John McCalle27ec8a2009-10-23 23:03:21 +0000172void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000173 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000174 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000175 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
Reid Spencer5f016e22007-07-11 17:01:13 +0000178void ASTContext::InitBuiltinTypes() {
179 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 // C99 6.2.5p19.
182 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 // C99 6.2.5p2.
185 InitBuiltinType(BoolTy, BuiltinType::Bool);
186 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000187 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 InitBuiltinType(CharTy, BuiltinType::Char_S);
189 else
190 InitBuiltinType(CharTy, BuiltinType::Char_U);
191 // C99 6.2.5p4.
192 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
193 InitBuiltinType(ShortTy, BuiltinType::Short);
194 InitBuiltinType(IntTy, BuiltinType::Int);
195 InitBuiltinType(LongTy, BuiltinType::Long);
196 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 // C99 6.2.5p6.
199 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
200 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
201 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
202 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
203 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // C99 6.2.5p10.
206 InitBuiltinType(FloatTy, BuiltinType::Float);
207 InitBuiltinType(DoubleTy, BuiltinType::Double);
208 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000209
Chris Lattner2df9ced2009-04-30 02:43:43 +0000210 // GNU extension, 128-bit integers.
211 InitBuiltinType(Int128Ty, BuiltinType::Int128);
212 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
213
Chris Lattner3a250322009-02-26 23:43:47 +0000214 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
215 InitBuiltinType(WCharTy, BuiltinType::WChar);
216 else // C99
217 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000218
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000219 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
220 InitBuiltinType(Char16Ty, BuiltinType::Char16);
221 else // C99
222 Char16Ty = getFromTargetType(Target.getChar16Type());
223
224 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
225 InitBuiltinType(Char32Ty, BuiltinType::Char32);
226 else // C99
227 Char32Ty = getFromTargetType(Target.getChar32Type());
228
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000230 InitBuiltinType(OverloadTy, BuiltinType::Overload);
231
232 // Placeholder type for type-dependent expressions whose type is
233 // completely unknown. No code should ever check a type against
234 // DependentTy and users should never see it; however, it is here to
235 // help diagnose failures to properly check for type-dependent
236 // expressions.
237 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238
Mike Stump1eb44332009-09-09 15:08:12 +0000239 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000240 // not yet been deduced.
241 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 // C99 6.2.5p11.
244 FloatComplexTy = getComplexType(FloatTy);
245 DoubleComplexTy = getComplexType(DoubleTy);
246 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247
Steve Naroff7e219e42007-10-15 14:41:52 +0000248 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Steve Naroffde2e22d2009-07-15 18:40:39 +0000250 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
251 ObjCIdTypedefType = QualType();
252 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000253 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000255 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000256 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
257 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000258 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000259
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000262 // void * type
263 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000264
265 // nullptr type (C++0x 2.14.7)
266 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000267}
268
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000269MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000270ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000271 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000272 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000273 = InstantiatedFromStaticDataMember.find(Var);
274 if (Pos == InstantiatedFromStaticDataMember.end())
275 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Douglas Gregor7caa6822009-07-24 20:34:43 +0000277 return Pos->second;
278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000281ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
282 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000283 assert(Inst->isStaticDataMember() && "Not a static data member");
284 assert(Tmpl->isStaticDataMember() && "Not a static data member");
285 assert(!InstantiatedFromStaticDataMember[Inst] &&
286 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000287 InstantiatedFromStaticDataMember[Inst]
288 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000289}
290
John McCall7ba107a2009-11-18 02:36:19 +0000291NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000292ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000293 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000294 = InstantiatedFromUsingDecl.find(UUD);
295 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000296 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Anders Carlsson0d8df782009-08-29 19:37:28 +0000298 return Pos->second;
299}
300
301void
John McCalled976492009-12-04 22:46:56 +0000302ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
303 assert((isa<UsingDecl>(Pattern) ||
304 isa<UnresolvedUsingValueDecl>(Pattern) ||
305 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
306 "pattern decl is not a using decl");
307 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
308 InstantiatedFromUsingDecl[Inst] = Pattern;
309}
310
311UsingShadowDecl *
312ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
313 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
314 = InstantiatedFromUsingShadowDecl.find(Inst);
315 if (Pos == InstantiatedFromUsingShadowDecl.end())
316 return 0;
317
318 return Pos->second;
319}
320
321void
322ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
323 UsingShadowDecl *Pattern) {
324 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
325 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000326}
327
Anders Carlssond8b285f2009-09-01 04:26:58 +0000328FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
329 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
330 = InstantiatedFromUnnamedFieldDecl.find(Field);
331 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
332 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Anders Carlssond8b285f2009-09-01 04:26:58 +0000334 return Pos->second;
335}
336
337void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
338 FieldDecl *Tmpl) {
339 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
340 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
341 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
342 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Anders Carlssond8b285f2009-09-01 04:26:58 +0000344 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
345}
346
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000347ASTContext::overridden_cxx_method_iterator
348ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
349 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
350 = OverriddenMethods.find(Method);
351 if (Pos == OverriddenMethods.end())
352 return 0;
353
354 return Pos->second.begin();
355}
356
357ASTContext::overridden_cxx_method_iterator
358ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
359 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
360 = OverriddenMethods.find(Method);
361 if (Pos == OverriddenMethods.end())
362 return 0;
363
364 return Pos->second.end();
365}
366
367void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
368 const CXXMethodDecl *Overridden) {
369 OverriddenMethods[Method].push_back(Overridden);
370}
371
Douglas Gregor2e222532009-07-02 17:08:52 +0000372namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000373 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000374 : std::binary_function<SourceRange, SourceRange, bool> {
375 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Douglas Gregor2e222532009-07-02 17:08:52 +0000377 public:
378 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 bool operator()(SourceRange X, SourceRange Y) {
381 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
382 }
383 };
384}
385
Chris Lattner464175b2007-07-18 17:52:12 +0000386//===----------------------------------------------------------------------===//
387// Type Sizing and Analysis
388//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000389
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000390/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
391/// scalar floating point type.
392const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000393 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000394 assert(BT && "Not a floating point type!");
395 switch (BT->getKind()) {
396 default: assert(0 && "Not a floating point type!");
397 case BuiltinType::Float: return Target.getFloatFormat();
398 case BuiltinType::Double: return Target.getDoubleFormat();
399 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
400 }
401}
402
Ken Dyck8b752f12010-01-27 17:10:57 +0000403/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000404/// specified decl. Note that bitfields do not have a valid alignment, so
405/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000406/// If @p RefAsPointee, references are treated like their underlying type
407/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000408CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000409 unsigned Align = Target.getCharWidth();
410
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000411 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000412 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000413
Chris Lattneraf707ab2009-01-24 21:53:27 +0000414 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
415 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000416 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000417 if (RefAsPointee)
418 T = RT->getPointeeType();
419 else
420 T = getPointerType(RT->getPointeeType());
421 }
422 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000423 unsigned MinWidth = Target.getLargeArrayMinWidth();
424 unsigned ArrayAlign = Target.getLargeArrayAlign();
425 if (isa<VariableArrayType>(T) && MinWidth != 0)
426 Align = std::max(Align, ArrayAlign);
427 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
428 unsigned Size = getTypeSize(CT);
429 if (MinWidth != 0 && MinWidth <= Size)
430 Align = std::max(Align, ArrayAlign);
431 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000432 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000433 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
434 T = cast<ArrayType>(T)->getElementType();
435
436 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
437 }
Charles Davis05f62472010-02-23 04:52:00 +0000438 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
439 // In the case of a field in a packed struct, we want the minimum
440 // of the alignment of the field and the alignment of the struct.
441 Align = std::min(Align,
442 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
443 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000444 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000445
Ken Dyck8b752f12010-01-27 17:10:57 +0000446 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000447}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000448
John McCallea1471e2010-05-20 01:18:31 +0000449std::pair<CharUnits, CharUnits>
450ASTContext::getTypeInfoInChars(const Type *T) {
451 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
452 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
453 CharUnits::fromQuantity(Info.second / getCharWidth()));
454}
455
456std::pair<CharUnits, CharUnits>
457ASTContext::getTypeInfoInChars(QualType T) {
458 return getTypeInfoInChars(T.getTypePtr());
459}
460
Chris Lattnera7674d82007-07-13 22:13:22 +0000461/// getTypeSize - Return the size of the specified type, in bits. This method
462/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000463///
464/// FIXME: Pointers into different addr spaces could have different sizes and
465/// alignment requirements: getPointerInfo should take an AddrSpace, this
466/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000467std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000468ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000469 uint64_t Width=0;
470 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000471 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000472#define TYPE(Class, Base)
473#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000474#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000475#define DEPENDENT_TYPE(Class, Base) case Type::Class:
476#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000477 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000478 break;
479
Chris Lattner692233e2007-07-13 22:27:08 +0000480 case Type::FunctionNoProto:
481 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000482 // GCC extension: alignof(function) = 32 bits
483 Width = 0;
484 Align = 32;
485 break;
486
Douglas Gregor72564e72009-02-26 23:50:07 +0000487 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000488 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000489 Width = 0;
490 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
491 break;
492
Steve Narofffb22d962007-08-30 01:06:46 +0000493 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000494 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner98be4942008-03-05 18:54:05 +0000496 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000497 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000498 Align = EltInfo.second;
499 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000500 }
Nate Begeman213541a2008-04-18 23:10:10 +0000501 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000502 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000503 const VectorType *VT = cast<VectorType>(T);
504 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
505 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000506 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000507 // If the alignment is not a power of 2, round up to the next power of 2.
508 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000509 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000510 Align = llvm::NextPowerOf2(Align);
511 Width = llvm::RoundUpToAlignment(Width, Align);
512 }
Chris Lattner030d8842007-07-19 22:06:24 +0000513 break;
514 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000515
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000516 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000517 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000518 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000519 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000520 // GCC extension: alignof(void) = 8 bits.
521 Width = 0;
522 Align = 8;
523 break;
524
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000525 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000526 Width = Target.getBoolWidth();
527 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000528 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000529 case BuiltinType::Char_S:
530 case BuiltinType::Char_U:
531 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000532 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000533 Width = Target.getCharWidth();
534 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000535 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000536 case BuiltinType::WChar:
537 Width = Target.getWCharWidth();
538 Align = Target.getWCharAlign();
539 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000540 case BuiltinType::Char16:
541 Width = Target.getChar16Width();
542 Align = Target.getChar16Align();
543 break;
544 case BuiltinType::Char32:
545 Width = Target.getChar32Width();
546 Align = Target.getChar32Align();
547 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000548 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000549 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000550 Width = Target.getShortWidth();
551 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000552 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000553 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000555 Width = Target.getIntWidth();
556 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000557 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000558 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000560 Width = Target.getLongWidth();
561 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000562 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000563 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000564 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000565 Width = Target.getLongLongWidth();
566 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000567 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000568 case BuiltinType::Int128:
569 case BuiltinType::UInt128:
570 Width = 128;
571 Align = 128; // int128_t is 128-bit aligned on all targets.
572 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000573 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000574 Width = Target.getFloatWidth();
575 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000576 break;
577 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000578 Width = Target.getDoubleWidth();
579 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000580 break;
581 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000582 Width = Target.getLongDoubleWidth();
583 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000584 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000585 case BuiltinType::NullPtr:
586 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
587 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000588 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000589 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000590 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000591 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000592 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000593 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000594 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000595 case Type::BlockPointer: {
596 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
597 Width = Target.getPointerWidth(AS);
598 Align = Target.getPointerAlign(AS);
599 break;
600 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000601 case Type::LValueReference:
602 case Type::RValueReference: {
603 // alignof and sizeof should never enter this code path here, so we go
604 // the pointer route.
605 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
606 Width = Target.getPointerWidth(AS);
607 Align = Target.getPointerAlign(AS);
608 break;
609 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000610 case Type::Pointer: {
611 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000612 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000613 Align = Target.getPointerAlign(AS);
614 break;
615 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000616 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000617 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000618 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000619 getTypeInfo(getPointerDiffType());
620 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000621 if (Pointee->isFunctionType())
622 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000623 Align = PtrDiffInfo.second;
624 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000625 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000626 case Type::Complex: {
627 // Complex types have the same alignment as their elements, but twice the
628 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000629 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000630 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000631 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000632 Align = EltInfo.second;
633 break;
634 }
John McCallc12c5bb2010-05-15 11:32:37 +0000635 case Type::ObjCObject:
636 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000637 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000638 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000639 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
640 Width = Layout.getSize();
641 Align = Layout.getAlignment();
642 break;
643 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000644 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000645 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000646 const TagType *TT = cast<TagType>(T);
647
648 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000649 Width = 1;
650 Align = 1;
651 break;
652 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Daniel Dunbar1d751182008-11-08 05:48:37 +0000654 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000655 return getTypeInfo(ET->getDecl()->getIntegerType());
656
Daniel Dunbar1d751182008-11-08 05:48:37 +0000657 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000658 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
659 Width = Layout.getSize();
660 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000661 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000662 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000663
Chris Lattner9fcfe922009-10-22 05:17:15 +0000664 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000665 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
666 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000667
Douglas Gregor18857642009-04-30 17:32:17 +0000668 case Type::Typedef: {
669 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000670 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000671 Align = std::max(Aligned->getMaxAlignment(),
672 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000673 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
674 } else
675 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000676 break;
Chris Lattner71763312008-04-06 22:05:18 +0000677 }
Douglas Gregor18857642009-04-30 17:32:17 +0000678
679 case Type::TypeOfExpr:
680 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
681 .getTypePtr());
682
683 case Type::TypeOf:
684 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
685
Anders Carlsson395b4752009-06-24 19:06:50 +0000686 case Type::Decltype:
687 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
688 .getTypePtr());
689
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000690 case Type::Elaborated:
691 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Douglas Gregor18857642009-04-30 17:32:17 +0000693 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000694 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000695 "Cannot request the size of a dependent type");
696 // FIXME: this is likely to be wrong once we support template
697 // aliases, since a template alias could refer to a typedef that
698 // has an __aligned__ attribute on it.
699 return getTypeInfo(getCanonicalType(T));
700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattner464175b2007-07-18 17:52:12 +0000702 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000703 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000704}
705
Ken Dyckbdc601b2009-12-22 14:23:30 +0000706/// getTypeSizeInChars - Return the size of the specified type, in characters.
707/// This method does not work on incomplete types.
708CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000709 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000710}
711CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000712 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000713}
714
Ken Dyck16e20cc2010-01-26 17:25:18 +0000715/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000716/// characters. This method does not work on incomplete types.
717CharUnits ASTContext::getTypeAlignInChars(QualType T) {
718 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
719}
720CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
721 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
722}
723
Chris Lattner34ebde42009-01-27 18:08:34 +0000724/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
725/// type for the current target in bits. This can be different than the ABI
726/// alignment in cases where it is beneficial for performance to overalign
727/// a data type.
728unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
729 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000730
731 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000732 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000733 T = CT->getElementType().getTypePtr();
734 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
735 T->isSpecificBuiltinType(BuiltinType::LongLong))
736 return std::max(ABIAlign, (unsigned)getTypeSize(T));
737
Chris Lattner34ebde42009-01-27 18:08:34 +0000738 return ABIAlign;
739}
740
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000741static void CollectLocalObjCIvars(ASTContext *Ctx,
742 const ObjCInterfaceDecl *OI,
743 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000744 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
745 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000746 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000747 if (!IVDecl->isInvalidDecl())
748 Fields.push_back(cast<FieldDecl>(IVDecl));
749 }
750}
751
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000752void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
753 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
754 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
755 CollectObjCIvars(SuperClass, Fields);
756 CollectLocalObjCIvars(this, OI, Fields);
757}
758
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000759/// ShallowCollectObjCIvars -
760/// Collect all ivars, including those synthesized, in the current class.
761///
762void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000763 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000764 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
765 E = OI->ivar_end(); I != E; ++I) {
766 Ivars.push_back(*I);
767 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000768
769 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000770}
771
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000772/// CollectNonClassIvars -
773/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000774/// This includes synthesized ivars (via @synthesize) and those in
775// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000776///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000777void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000778 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000779 // Find ivars declared in class extension.
780 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
781 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
782 E = CDecl->ivar_end(); I != E; ++I) {
783 Ivars.push_back(*I);
784 }
785 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000786
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000787 // Also add any ivar defined in this class's implementation. This
788 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000789 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
790 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
791 E = ImplDecl->ivar_end(); I != E; ++I)
792 Ivars.push_back(*I);
793 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000794}
795
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000796/// CollectInheritedProtocols - Collect all protocols in current class and
797/// those inherited by it.
798void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000799 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000800 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
801 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
802 PE = OI->protocol_end(); P != PE; ++P) {
803 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000804 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000805 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000806 PE = Proto->protocol_end(); P != PE; ++P) {
807 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000808 CollectInheritedProtocols(*P, Protocols);
809 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000810 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000811
812 // Categories of this Interface.
813 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
814 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
815 CollectInheritedProtocols(CDeclChain, Protocols);
816 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
817 while (SD) {
818 CollectInheritedProtocols(SD, Protocols);
819 SD = SD->getSuperClass();
820 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000821 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000822 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
823 PE = OC->protocol_end(); P != PE; ++P) {
824 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000825 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000826 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
827 PE = Proto->protocol_end(); P != PE; ++P)
828 CollectInheritedProtocols(*P, Protocols);
829 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000830 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000831 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
832 PE = OP->protocol_end(); P != PE; ++P) {
833 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000834 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000835 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
836 PE = Proto->protocol_end(); P != PE; ++P)
837 CollectInheritedProtocols(*P, Protocols);
838 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000839 }
840}
841
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000842unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
843 unsigned count = 0;
844 // Count ivars declared in class extension.
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000845 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension())
846 count += CDecl->ivar_size();
847
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000848 // Count ivar defined in this class's implementation. This
849 // includes synthesized ivars.
850 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000851 count += ImplDecl->ivar_size();
852
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000853 return count;
854}
855
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000856/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
857ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
858 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
859 I = ObjCImpls.find(D);
860 if (I != ObjCImpls.end())
861 return cast<ObjCImplementationDecl>(I->second);
862 return 0;
863}
864/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
865ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
866 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
867 I = ObjCImpls.find(D);
868 if (I != ObjCImpls.end())
869 return cast<ObjCCategoryImplDecl>(I->second);
870 return 0;
871}
872
873/// \brief Set the implementation of ObjCInterfaceDecl.
874void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
875 ObjCImplementationDecl *ImplD) {
876 assert(IFaceD && ImplD && "Passed null params");
877 ObjCImpls[IFaceD] = ImplD;
878}
879/// \brief Set the implementation of ObjCCategoryDecl.
880void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
881 ObjCCategoryImplDecl *ImplD) {
882 assert(CatD && ImplD && "Passed null params");
883 ObjCImpls[CatD] = ImplD;
884}
885
John McCalla93c9342009-12-07 02:54:59 +0000886/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000887///
John McCalla93c9342009-12-07 02:54:59 +0000888/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000889/// the TypeLoc wrappers.
890///
891/// \param T the type that will be the basis for type source info. This type
892/// should refer to how the declarator was written in source code, not to
893/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000894TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000895 unsigned DataSize) {
896 if (!DataSize)
897 DataSize = TypeLoc::getFullDataSizeForType(T);
898 else
899 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +0000900 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +0000901
John McCalla93c9342009-12-07 02:54:59 +0000902 TypeSourceInfo *TInfo =
903 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
904 new (TInfo) TypeSourceInfo(T);
905 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000906}
907
John McCalla93c9342009-12-07 02:54:59 +0000908TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +0000909 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +0000910 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +0000911 DI->getTypeLoc().initialize(L);
912 return DI;
913}
914
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000915const ASTRecordLayout &
916ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
917 return getObjCLayout(D, 0);
918}
919
920const ASTRecordLayout &
921ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
922 return getObjCLayout(D->getClassInterface(), D);
923}
924
Chris Lattnera7674d82007-07-13 22:13:22 +0000925//===----------------------------------------------------------------------===//
926// Type creation/memoization methods
927//===----------------------------------------------------------------------===//
928
John McCall0953e762009-09-24 19:53:00 +0000929QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
930 unsigned Fast = Quals.getFastQualifiers();
931 Quals.removeFastQualifiers();
932
933 // Check if we've already instantiated this type.
934 llvm::FoldingSetNodeID ID;
935 ExtQuals::Profile(ID, TypeNode, Quals);
936 void *InsertPos = 0;
937 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
938 assert(EQ->getQualifiers() == Quals);
939 QualType T = QualType(EQ, Fast);
940 return T;
941 }
942
John McCall6b304a02009-09-24 23:30:46 +0000943 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +0000944 ExtQualNodes.InsertNode(New, InsertPos);
945 QualType T = QualType(New, Fast);
946 return T;
947}
948
949QualType ASTContext::getVolatileType(QualType T) {
950 QualType CanT = getCanonicalType(T);
951 if (CanT.isVolatileQualified()) return T;
952
953 QualifierCollector Quals;
954 const Type *TypeNode = Quals.strip(T);
955 Quals.addVolatile();
956
957 return getExtQualType(TypeNode, Quals);
958}
959
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000960QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000961 QualType CanT = getCanonicalType(T);
962 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000963 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000964
John McCall0953e762009-09-24 19:53:00 +0000965 // If we are composing extended qualifiers together, merge together
966 // into one ExtQuals node.
967 QualifierCollector Quals;
968 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000969
John McCall0953e762009-09-24 19:53:00 +0000970 // If this type already has an address space specified, it cannot get
971 // another one.
972 assert(!Quals.hasAddressSpace() &&
973 "Type cannot be in multiple addr spaces!");
974 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000975
John McCall0953e762009-09-24 19:53:00 +0000976 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000977}
978
Chris Lattnerb7d25532009-02-18 22:53:11 +0000979QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +0000980 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000981 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000982 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000983 return T;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000985 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000986 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000987 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000988 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
989 return getPointerType(ResultType);
990 }
991 }
Mike Stump1eb44332009-09-09 15:08:12 +0000992
John McCall0953e762009-09-24 19:53:00 +0000993 // If we are composing extended qualifiers together, merge together
994 // into one ExtQuals node.
995 QualifierCollector Quals;
996 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
John McCall0953e762009-09-24 19:53:00 +0000998 // If this type already has an ObjCGC specified, it cannot get
999 // another one.
1000 assert(!Quals.hasObjCGCAttr() &&
1001 "Type cannot have multiple ObjCGCs!");
1002 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001003
John McCall0953e762009-09-24 19:53:00 +00001004 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001005}
Chris Lattnera7674d82007-07-13 22:13:22 +00001006
Rafael Espindola264ba482010-03-30 20:24:48 +00001007static QualType getExtFunctionType(ASTContext& Context, QualType T,
1008 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001009 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001010 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1011 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001012 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001013 if (ResultType == Pointee)
1014 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001015
1016 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001017 } else if (const BlockPointerType *BlockPointer
1018 = T->getAs<BlockPointerType>()) {
1019 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001020 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001021 if (ResultType == Pointee)
1022 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001023
1024 ResultType = Context.getBlockPointerType(ResultType);
1025 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001026 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001027 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001028
Douglas Gregor43c79c22009-12-09 00:47:37 +00001029 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001030 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001031 Info);
John McCall0953e762009-09-24 19:53:00 +00001032 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001033 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001034 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001035 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1036 FPT->getNumArgs(), FPT->isVariadic(),
1037 FPT->getTypeQuals(),
1038 FPT->hasExceptionSpec(),
1039 FPT->hasAnyExceptionSpec(),
1040 FPT->getNumExceptions(),
1041 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001042 Info);
John McCall0953e762009-09-24 19:53:00 +00001043 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001044 } else
1045 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001046
1047 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1048}
1049
1050QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001051 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001052 return getExtFunctionType(*this, T,
1053 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001054}
1055
1056QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001057 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001058 return getExtFunctionType(*this, T,
1059 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001060}
1061
Rafael Espindola425ef722010-03-30 22:15:11 +00001062QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1063 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1064 return getExtFunctionType(*this, T,
1065 Info.withRegParm(RegParm));
1066}
1067
Reid Spencer5f016e22007-07-11 17:01:13 +00001068/// getComplexType - Return the uniqued reference to the type for a complex
1069/// number with the specified element type.
1070QualType ASTContext::getComplexType(QualType T) {
1071 // Unique pointers, to guarantee there is only one pointer of a particular
1072 // structure.
1073 llvm::FoldingSetNodeID ID;
1074 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 void *InsertPos = 0;
1077 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1078 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Reid Spencer5f016e22007-07-11 17:01:13 +00001080 // If the pointee type isn't canonical, this won't be a canonical type either,
1081 // so fill in the canonical type field.
1082 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001083 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001084 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 // Get the new insert position for the node we care about.
1087 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001088 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 }
John McCall6b304a02009-09-24 23:30:46 +00001090 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 Types.push_back(New);
1092 ComplexTypes.InsertNode(New, InsertPos);
1093 return QualType(New, 0);
1094}
1095
Reid Spencer5f016e22007-07-11 17:01:13 +00001096/// getPointerType - Return the uniqued reference to the type for a pointer to
1097/// the specified type.
1098QualType ASTContext::getPointerType(QualType T) {
1099 // Unique pointers, to guarantee there is only one pointer of a particular
1100 // structure.
1101 llvm::FoldingSetNodeID ID;
1102 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 void *InsertPos = 0;
1105 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1106 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 // If the pointee type isn't canonical, this won't be a canonical type either,
1109 // so fill in the canonical type field.
1110 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001111 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001112 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 // Get the new insert position for the node we care about.
1115 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001116 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 }
John McCall6b304a02009-09-24 23:30:46 +00001118 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 Types.push_back(New);
1120 PointerTypes.InsertNode(New, InsertPos);
1121 return QualType(New, 0);
1122}
1123
Mike Stump1eb44332009-09-09 15:08:12 +00001124/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001125/// a pointer to the specified block.
1126QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001127 assert(T->isFunctionType() && "block of function types only");
1128 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001129 // structure.
1130 llvm::FoldingSetNodeID ID;
1131 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Steve Naroff5618bd42008-08-27 16:04:49 +00001133 void *InsertPos = 0;
1134 if (BlockPointerType *PT =
1135 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1136 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001137
1138 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001139 // type either so fill in the canonical type field.
1140 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001141 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001142 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Steve Naroff5618bd42008-08-27 16:04:49 +00001144 // Get the new insert position for the node we care about.
1145 BlockPointerType *NewIP =
1146 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001147 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001148 }
John McCall6b304a02009-09-24 23:30:46 +00001149 BlockPointerType *New
1150 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001151 Types.push_back(New);
1152 BlockPointerTypes.InsertNode(New, InsertPos);
1153 return QualType(New, 0);
1154}
1155
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001156/// getLValueReferenceType - Return the uniqued reference to the type for an
1157/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001158QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 // Unique pointers, to guarantee there is only one pointer of a particular
1160 // structure.
1161 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001162 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001163
1164 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001165 if (LValueReferenceType *RT =
1166 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001168
John McCall54e14c42009-10-22 22:37:11 +00001169 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 // If the referencee type isn't canonical, this won't be a canonical type
1172 // either, so fill in the canonical type field.
1173 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001174 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1175 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1176 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001177
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001179 LValueReferenceType *NewIP =
1180 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001181 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 }
1183
John McCall6b304a02009-09-24 23:30:46 +00001184 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001185 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1186 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001188 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001189
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001190 return QualType(New, 0);
1191}
1192
1193/// getRValueReferenceType - Return the uniqued reference to the type for an
1194/// rvalue reference to the specified type.
1195QualType ASTContext::getRValueReferenceType(QualType T) {
1196 // Unique pointers, to guarantee there is only one pointer of a particular
1197 // structure.
1198 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001199 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001200
1201 void *InsertPos = 0;
1202 if (RValueReferenceType *RT =
1203 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1204 return QualType(RT, 0);
1205
John McCall54e14c42009-10-22 22:37:11 +00001206 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1207
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001208 // If the referencee type isn't canonical, this won't be a canonical type
1209 // either, so fill in the canonical type field.
1210 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001211 if (InnerRef || !T.isCanonical()) {
1212 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1213 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001214
1215 // Get the new insert position for the node we care about.
1216 RValueReferenceType *NewIP =
1217 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1218 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1219 }
1220
John McCall6b304a02009-09-24 23:30:46 +00001221 RValueReferenceType *New
1222 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001223 Types.push_back(New);
1224 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 return QualType(New, 0);
1226}
1227
Sebastian Redlf30208a2009-01-24 21:16:55 +00001228/// getMemberPointerType - Return the uniqued reference to the type for a
1229/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001230QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001231 // Unique pointers, to guarantee there is only one pointer of a particular
1232 // structure.
1233 llvm::FoldingSetNodeID ID;
1234 MemberPointerType::Profile(ID, T, Cls);
1235
1236 void *InsertPos = 0;
1237 if (MemberPointerType *PT =
1238 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1239 return QualType(PT, 0);
1240
1241 // If the pointee or class type isn't canonical, this won't be a canonical
1242 // type either, so fill in the canonical type field.
1243 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001244 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001245 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1246
1247 // Get the new insert position for the node we care about.
1248 MemberPointerType *NewIP =
1249 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1250 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1251 }
John McCall6b304a02009-09-24 23:30:46 +00001252 MemberPointerType *New
1253 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001254 Types.push_back(New);
1255 MemberPointerTypes.InsertNode(New, InsertPos);
1256 return QualType(New, 0);
1257}
1258
Mike Stump1eb44332009-09-09 15:08:12 +00001259/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001260/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001261QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001262 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001263 ArrayType::ArraySizeModifier ASM,
1264 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001265 assert((EltTy->isDependentType() ||
1266 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001267 "Constant array of VLAs is illegal!");
1268
Chris Lattner38aeec72009-05-13 04:12:56 +00001269 // Convert the array size into a canonical width matching the pointer size for
1270 // the target.
1271 llvm::APInt ArySize(ArySizeIn);
1272 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001275 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001278 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001279 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // If the element type isn't canonical, this won't be a canonical type either,
1283 // so fill in the canonical type field.
1284 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001285 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001286 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001287 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001289 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001290 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001291 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCall6b304a02009-09-24 23:30:46 +00001294 ConstantArrayType *New = new(*this,TypeAlignment)
1295 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001296 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 Types.push_back(New);
1298 return QualType(New, 0);
1299}
1300
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001301/// getVariableArrayType - Returns a non-unique reference to the type for a
1302/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001303QualType ASTContext::getVariableArrayType(QualType EltTy,
1304 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001305 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001306 unsigned EltTypeQuals,
1307 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001308 // Since we don't unique expressions, it isn't possible to unique VLA's
1309 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001310 QualType CanonType;
1311
1312 if (!EltTy.isCanonical()) {
1313 if (NumElts)
1314 NumElts->Retain();
1315 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1316 EltTypeQuals, Brackets);
1317 }
1318
John McCall6b304a02009-09-24 23:30:46 +00001319 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001320 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001321
1322 VariableArrayTypes.push_back(New);
1323 Types.push_back(New);
1324 return QualType(New, 0);
1325}
1326
Douglas Gregor898574e2008-12-05 23:32:09 +00001327/// getDependentSizedArrayType - Returns a non-unique reference to
1328/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001329/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001330QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1331 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001332 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001333 unsigned EltTypeQuals,
1334 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001335 assert((!NumElts || NumElts->isTypeDependent() ||
1336 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001337 "Size must be type- or value-dependent!");
1338
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001339 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001340 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001341 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001342
1343 if (NumElts) {
1344 // Dependently-sized array types that do not have a specified
1345 // number of elements will have their sizes deduced from an
1346 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001347 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1348 EltTypeQuals, NumElts);
1349
1350 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1351 }
1352
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001353 DependentSizedArrayType *New;
1354 if (Canon) {
1355 // We already have a canonical version of this array type; use it as
1356 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001357 New = new (*this, TypeAlignment)
1358 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1359 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001360 } else {
1361 QualType CanonEltTy = getCanonicalType(EltTy);
1362 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001363 New = new (*this, TypeAlignment)
1364 DependentSizedArrayType(*this, EltTy, QualType(),
1365 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001366
Douglas Gregor789b1f62010-02-04 18:10:26 +00001367 if (NumElts) {
1368 DependentSizedArrayType *CanonCheck
1369 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1370 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1371 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001372 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001373 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001374 } else {
1375 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1376 ASM, EltTypeQuals,
1377 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001378 New = new (*this, TypeAlignment)
1379 DependentSizedArrayType(*this, EltTy, Canon,
1380 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001381 }
1382 }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Douglas Gregor898574e2008-12-05 23:32:09 +00001384 Types.push_back(New);
1385 return QualType(New, 0);
1386}
1387
Eli Friedmanc5773c42008-02-15 18:16:39 +00001388QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1389 ArrayType::ArraySizeModifier ASM,
1390 unsigned EltTypeQuals) {
1391 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001392 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001393
1394 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001395 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001396 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1397 return QualType(ATP, 0);
1398
1399 // If the element type isn't canonical, this won't be a canonical type
1400 // either, so fill in the canonical type field.
1401 QualType Canonical;
1402
John McCall467b27b2009-10-22 20:10:53 +00001403 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001404 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001405 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001406
1407 // Get the new insert position for the node we care about.
1408 IncompleteArrayType *NewIP =
1409 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001410 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001411 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001412
John McCall6b304a02009-09-24 23:30:46 +00001413 IncompleteArrayType *New = new (*this, TypeAlignment)
1414 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001415
1416 IncompleteArrayTypes.InsertNode(New, InsertPos);
1417 Types.push_back(New);
1418 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001419}
1420
Steve Naroff73322922007-07-18 18:00:27 +00001421/// getVectorType - Return the unique reference to a vector type of
1422/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001423QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1424 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Chris Lattnerf52ab252008-04-06 22:59:24 +00001427 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001428 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 // Check if we've already instantiated a vector of this type.
1431 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001432 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1433 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 void *InsertPos = 0;
1435 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1436 return QualType(VTP, 0);
1437
1438 // If the element type isn't canonical, this won't be a canonical type either,
1439 // so fill in the canonical type field.
1440 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001441 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1442 Canonical = getVectorType(getCanonicalType(vecType),
1443 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // Get the new insert position for the node we care about.
1446 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001447 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 }
John McCall6b304a02009-09-24 23:30:46 +00001449 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001450 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 VectorTypes.InsertNode(New, InsertPos);
1452 Types.push_back(New);
1453 return QualType(New, 0);
1454}
1455
Nate Begeman213541a2008-04-18 23:10:10 +00001456/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001457/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001458QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001459 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattnerf52ab252008-04-06 22:59:24 +00001461 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001462 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Steve Naroff73322922007-07-18 18:00:27 +00001464 // Check if we've already instantiated a vector of this type.
1465 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001466 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001467 void *InsertPos = 0;
1468 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1469 return QualType(VTP, 0);
1470
1471 // If the element type isn't canonical, this won't be a canonical type either,
1472 // so fill in the canonical type field.
1473 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001474 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001475 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Steve Naroff73322922007-07-18 18:00:27 +00001477 // Get the new insert position for the node we care about.
1478 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001479 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001480 }
John McCall6b304a02009-09-24 23:30:46 +00001481 ExtVectorType *New = new (*this, TypeAlignment)
1482 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001483 VectorTypes.InsertNode(New, InsertPos);
1484 Types.push_back(New);
1485 return QualType(New, 0);
1486}
1487
Mike Stump1eb44332009-09-09 15:08:12 +00001488QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001489 Expr *SizeExpr,
1490 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001491 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001492 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001493 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001495 void *InsertPos = 0;
1496 DependentSizedExtVectorType *Canon
1497 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1498 DependentSizedExtVectorType *New;
1499 if (Canon) {
1500 // We already have a canonical version of this array type; use it as
1501 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001502 New = new (*this, TypeAlignment)
1503 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1504 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001505 } else {
1506 QualType CanonVecTy = getCanonicalType(vecType);
1507 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001508 New = new (*this, TypeAlignment)
1509 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1510 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001511
1512 DependentSizedExtVectorType *CanonCheck
1513 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1514 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1515 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001516 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1517 } else {
1518 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1519 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001520 New = new (*this, TypeAlignment)
1521 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001522 }
1523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001525 Types.push_back(New);
1526 return QualType(New, 0);
1527}
1528
Douglas Gregor72564e72009-02-26 23:50:07 +00001529/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001530///
Rafael Espindola264ba482010-03-30 20:24:48 +00001531QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1532 const FunctionType::ExtInfo &Info) {
1533 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 // Unique functions, to guarantee there is only one function of a particular
1535 // structure.
1536 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001537 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001540 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001541 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001545 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001546 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001547 Canonical =
1548 getFunctionNoProtoType(getCanonicalType(ResultTy),
1549 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001552 FunctionNoProtoType *NewIP =
1553 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001554 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 }
Mike Stump1eb44332009-09-09 15:08:12 +00001556
John McCall6b304a02009-09-24 23:30:46 +00001557 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001558 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001560 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 return QualType(New, 0);
1562}
1563
1564/// getFunctionType - Return a normal function type with a typed argument
1565/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001566QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001567 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001568 unsigned TypeQuals, bool hasExceptionSpec,
1569 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001570 const QualType *ExArray,
1571 const FunctionType::ExtInfo &Info) {
1572 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // Unique functions, to guarantee there is only one function of a particular
1574 // structure.
1575 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001576 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001577 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001578 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579
1580 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001581 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001582 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001584
1585 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001586 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001588 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 isCanonical = false;
1590
1591 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001592 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001594 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 llvm::SmallVector<QualType, 16> CanonicalArgs;
1596 CanonicalArgs.reserve(NumArgs);
1597 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001598 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001599
Chris Lattnerf52ab252008-04-06 22:59:24 +00001600 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001601 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001602 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001603 false, 0, 0,
1604 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001605
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001607 FunctionProtoType *NewIP =
1608 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001609 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001611
Douglas Gregor72564e72009-02-26 23:50:07 +00001612 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001613 // for two variable size arrays (for parameter and exception types) at the
1614 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001615 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001616 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1617 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001618 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001619 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001620 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001621 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001623 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 return QualType(FTP, 0);
1625}
1626
John McCall3cb0ebd2010-03-10 03:28:59 +00001627#ifndef NDEBUG
1628static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1629 if (!isa<CXXRecordDecl>(D)) return false;
1630 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1631 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1632 return true;
1633 if (RD->getDescribedClassTemplate() &&
1634 !isa<ClassTemplateSpecializationDecl>(RD))
1635 return true;
1636 return false;
1637}
1638#endif
1639
1640/// getInjectedClassNameType - Return the unique reference to the
1641/// injected class name type for the specified templated declaration.
1642QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1643 QualType TST) {
1644 assert(NeedsInjectedClassNameType(Decl));
1645 if (Decl->TypeForDecl) {
1646 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1647 } else if (CXXRecordDecl *PrevDecl
1648 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1649 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1650 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1651 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1652 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001653 Decl->TypeForDecl =
1654 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001655 Types.push_back(Decl->TypeForDecl);
1656 }
1657 return QualType(Decl->TypeForDecl, 0);
1658}
1659
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001660/// getTypeDeclType - Return the unique reference to the type for the
1661/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001662QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001663 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001664 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001665
John McCall19c85762010-02-16 03:57:14 +00001666 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001667 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001668
John McCallbecb8d52010-03-10 06:48:02 +00001669 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1670 "Template type parameter types are always available.");
1671
John McCall19c85762010-02-16 03:57:14 +00001672 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001673 assert(!Record->getPreviousDeclaration() &&
1674 "struct/union has previous declaration");
1675 assert(!NeedsInjectedClassNameType(Record));
1676 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001677 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001678 assert(!Enum->getPreviousDeclaration() &&
1679 "enum has previous declaration");
1680 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001681 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001682 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1683 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001684 } else
John McCallbecb8d52010-03-10 06:48:02 +00001685 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001686
John McCallbecb8d52010-03-10 06:48:02 +00001687 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001688 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001689}
1690
Reid Spencer5f016e22007-07-11 17:01:13 +00001691/// getTypedefType - Return the unique reference to the type for the
1692/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001693QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Chris Lattnerf52ab252008-04-06 22:59:24 +00001696 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001697 Decl->TypeForDecl = new(*this, TypeAlignment)
1698 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 Types.push_back(Decl->TypeForDecl);
1700 return QualType(Decl->TypeForDecl, 0);
1701}
1702
John McCall49a832b2009-10-18 09:09:24 +00001703/// \brief Retrieve a substitution-result type.
1704QualType
1705ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1706 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001707 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001708 && "replacement types must always be canonical");
1709
1710 llvm::FoldingSetNodeID ID;
1711 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1712 void *InsertPos = 0;
1713 SubstTemplateTypeParmType *SubstParm
1714 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1715
1716 if (!SubstParm) {
1717 SubstParm = new (*this, TypeAlignment)
1718 SubstTemplateTypeParmType(Parm, Replacement);
1719 Types.push_back(SubstParm);
1720 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1721 }
1722
1723 return QualType(SubstParm, 0);
1724}
1725
Douglas Gregorfab9d672009-02-05 23:33:38 +00001726/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001727/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001728/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001729QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001730 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001731 IdentifierInfo *Name) {
1732 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001733 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001734 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001735 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001736 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1737
1738 if (TypeParm)
1739 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001741 if (Name) {
1742 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001743 TypeParm = new (*this, TypeAlignment)
1744 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001745
1746 TemplateTypeParmType *TypeCheck
1747 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1748 assert(!TypeCheck && "Template type parameter canonical type broken");
1749 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001750 } else
John McCall6b304a02009-09-24 23:30:46 +00001751 TypeParm = new (*this, TypeAlignment)
1752 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001753
1754 Types.push_back(TypeParm);
1755 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1756
1757 return QualType(TypeParm, 0);
1758}
1759
John McCall3cb0ebd2010-03-10 03:28:59 +00001760TypeSourceInfo *
1761ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1762 SourceLocation NameLoc,
1763 const TemplateArgumentListInfo &Args,
1764 QualType CanonType) {
1765 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1766
1767 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1768 TemplateSpecializationTypeLoc TL
1769 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1770 TL.setTemplateNameLoc(NameLoc);
1771 TL.setLAngleLoc(Args.getLAngleLoc());
1772 TL.setRAngleLoc(Args.getRAngleLoc());
1773 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1774 TL.setArgLocInfo(i, Args[i].getLocInfo());
1775 return DI;
1776}
1777
Mike Stump1eb44332009-09-09 15:08:12 +00001778QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001779ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001780 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001781 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001782 unsigned NumArgs = Args.size();
1783
John McCall833ca992009-10-29 08:12:44 +00001784 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1785 ArgVec.reserve(NumArgs);
1786 for (unsigned i = 0; i != NumArgs; ++i)
1787 ArgVec.push_back(Args[i].getArgument());
1788
John McCall31f17ec2010-04-27 00:57:59 +00001789 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001790 Canon);
John McCall833ca992009-10-29 08:12:44 +00001791}
1792
1793QualType
1794ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001795 const TemplateArgument *Args,
1796 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001797 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001798 if (!Canon.isNull())
1799 Canon = getCanonicalType(Canon);
1800 else {
1801 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001802 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1803 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1804 CanonArgs.reserve(NumArgs);
1805 for (unsigned I = 0; I != NumArgs; ++I)
1806 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1807
1808 // Determine whether this canonical template specialization type already
1809 // exists.
1810 llvm::FoldingSetNodeID ID;
John McCall71d74bc2010-06-13 09:25:03 +00001811 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001812 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001813
1814 void *InsertPos = 0;
1815 TemplateSpecializationType *Spec
1816 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Douglas Gregor1275ae02009-07-28 23:00:59 +00001818 if (!Spec) {
1819 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001820 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001821 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001822 TypeAlignment);
John McCall71d74bc2010-06-13 09:25:03 +00001823 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001824 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001825 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001826 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001827 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001828 }
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Douglas Gregorb88e8882009-07-30 17:40:51 +00001830 if (Canon.isNull())
1831 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001832 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001833 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001834 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001835
Douglas Gregor1275ae02009-07-28 23:00:59 +00001836 // Allocate the (non-canonical) template specialization type, but don't
1837 // try to unique it: these types typically have location information that
1838 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001839 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001840 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001841 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001842 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001843 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001844 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001845 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregor55f6b142009-02-09 18:46:07 +00001847 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001848 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001849}
1850
Mike Stump1eb44332009-09-09 15:08:12 +00001851QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001852ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1853 NestedNameSpecifier *NNS,
1854 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001855 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001856 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001857
1858 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001859 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001860 if (T)
1861 return QualType(T, 0);
1862
Douglas Gregor789b1f62010-02-04 18:10:26 +00001863 QualType Canon = NamedType;
1864 if (!Canon.isCanonical()) {
1865 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001866 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1867 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001868 (void)CheckT;
1869 }
1870
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001871 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001872 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001873 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001874 return QualType(T, 0);
1875}
1876
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001877QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1878 NestedNameSpecifier *NNS,
1879 const IdentifierInfo *Name,
1880 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00001881 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1882
1883 if (Canon.isNull()) {
1884 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001885 ElaboratedTypeKeyword CanonKeyword = Keyword;
1886 if (Keyword == ETK_None)
1887 CanonKeyword = ETK_Typename;
1888
1889 if (CanonNNS != NNS || CanonKeyword != Keyword)
1890 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00001891 }
1892
1893 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001894 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00001895
1896 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00001897 DependentNameType *T
1898 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00001899 if (T)
1900 return QualType(T, 0);
1901
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001902 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00001903 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00001904 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001905 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001906}
1907
Mike Stump1eb44332009-09-09 15:08:12 +00001908QualType
John McCall33500952010-06-11 00:33:02 +00001909ASTContext::getDependentTemplateSpecializationType(
1910 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001911 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00001912 const IdentifierInfo *Name,
1913 const TemplateArgumentListInfo &Args) {
1914 // TODO: avoid this copy
1915 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
1916 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1917 ArgCopy.push_back(Args[I].getArgument());
1918 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
1919 ArgCopy.size(),
1920 ArgCopy.data());
1921}
1922
1923QualType
1924ASTContext::getDependentTemplateSpecializationType(
1925 ElaboratedTypeKeyword Keyword,
1926 NestedNameSpecifier *NNS,
1927 const IdentifierInfo *Name,
1928 unsigned NumArgs,
1929 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00001930 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1931
Douglas Gregor789b1f62010-02-04 18:10:26 +00001932 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00001933 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
1934 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001935
1936 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00001937 DependentTemplateSpecializationType *T
1938 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001939 if (T)
1940 return QualType(T, 0);
1941
John McCall33500952010-06-11 00:33:02 +00001942 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001943
John McCall33500952010-06-11 00:33:02 +00001944 ElaboratedTypeKeyword CanonKeyword = Keyword;
1945 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
1946
1947 bool AnyNonCanonArgs = false;
1948 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
1949 for (unsigned I = 0; I != NumArgs; ++I) {
1950 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
1951 if (!CanonArgs[I].structurallyEquals(Args[I]))
1952 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00001953 }
1954
John McCall33500952010-06-11 00:33:02 +00001955 QualType Canon;
1956 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
1957 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
1958 Name, NumArgs,
1959 CanonArgs.data());
1960
1961 // Find the insert position again.
1962 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1963 }
1964
1965 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
1966 sizeof(TemplateArgument) * NumArgs),
1967 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00001968 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00001969 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00001970 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00001971 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001972 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001973}
1974
Chris Lattner88cb27a2008-04-07 04:56:42 +00001975/// CmpProtocolNames - Comparison predicate for sorting protocols
1976/// alphabetically.
1977static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1978 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001979 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001980}
1981
John McCallc12c5bb2010-05-15 11:32:37 +00001982static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00001983 unsigned NumProtocols) {
1984 if (NumProtocols == 0) return true;
1985
1986 for (unsigned i = 1; i != NumProtocols; ++i)
1987 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1988 return false;
1989 return true;
1990}
1991
1992static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00001993 unsigned &NumProtocols) {
1994 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattner88cb27a2008-04-07 04:56:42 +00001996 // Sort protocols, keyed by name.
1997 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1998
1999 // Remove duplicates.
2000 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2001 NumProtocols = ProtocolsEnd-Protocols;
2002}
2003
John McCallc12c5bb2010-05-15 11:32:37 +00002004QualType ASTContext::getObjCObjectType(QualType BaseType,
2005 ObjCProtocolDecl * const *Protocols,
2006 unsigned NumProtocols) {
2007 // If the base type is an interface and there aren't any protocols
2008 // to add, then the interface type will do just fine.
2009 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2010 return BaseType;
2011
2012 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002013 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002014 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002015 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002016 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2017 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002018
John McCallc12c5bb2010-05-15 11:32:37 +00002019 // Build the canonical type, which has the canonical base type and
2020 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002021 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002022 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2023 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2024 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002025 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2026 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002027 unsigned UniqueCount = NumProtocols;
2028
John McCall54e14c42009-10-22 22:37:11 +00002029 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002030 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2031 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002032 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002033 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2034 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002035 }
2036
2037 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002038 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2039 }
2040
2041 unsigned Size = sizeof(ObjCObjectTypeImpl);
2042 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2043 void *Mem = Allocate(Size, TypeAlignment);
2044 ObjCObjectTypeImpl *T =
2045 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2046
2047 Types.push_back(T);
2048 ObjCObjectTypes.InsertNode(T, InsertPos);
2049 return QualType(T, 0);
2050}
2051
2052/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2053/// the given object type.
2054QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2055 llvm::FoldingSetNodeID ID;
2056 ObjCObjectPointerType::Profile(ID, ObjectT);
2057
2058 void *InsertPos = 0;
2059 if (ObjCObjectPointerType *QT =
2060 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2061 return QualType(QT, 0);
2062
2063 // Find the canonical object type.
2064 QualType Canonical;
2065 if (!ObjectT.isCanonical()) {
2066 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2067
2068 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002069 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2070 }
2071
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002072 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002073 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2074 ObjCObjectPointerType *QType =
2075 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002077 Types.push_back(QType);
2078 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002079 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002080}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002081
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002082/// getObjCInterfaceType - Return the unique reference to the type for the
2083/// specified ObjC interface decl. The list of protocols is optional.
John McCallc12c5bb2010-05-15 11:32:37 +00002084QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2085 if (Decl->TypeForDecl)
2086 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
John McCallc12c5bb2010-05-15 11:32:37 +00002088 // FIXME: redeclarations?
2089 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2090 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2091 Decl->TypeForDecl = T;
2092 Types.push_back(T);
2093 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002094}
2095
Douglas Gregor72564e72009-02-26 23:50:07 +00002096/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2097/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002098/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002099/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002100/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002101QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002102 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002103 if (tofExpr->isTypeDependent()) {
2104 llvm::FoldingSetNodeID ID;
2105 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregorb1975722009-07-30 23:18:24 +00002107 void *InsertPos = 0;
2108 DependentTypeOfExprType *Canon
2109 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2110 if (Canon) {
2111 // We already have a "canonical" version of an identical, dependent
2112 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002113 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002114 QualType((TypeOfExprType*)Canon, 0));
2115 }
2116 else {
2117 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002118 Canon
2119 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002120 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2121 toe = Canon;
2122 }
2123 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002124 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002125 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002126 }
Steve Naroff9752f252007-08-01 18:02:17 +00002127 Types.push_back(toe);
2128 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002129}
2130
Steve Naroff9752f252007-08-01 18:02:17 +00002131/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2132/// TypeOfType AST's. The only motivation to unique these nodes would be
2133/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002134/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002135/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002136QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002137 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002138 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002139 Types.push_back(tot);
2140 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002141}
2142
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002143/// getDecltypeForExpr - Given an expr, will return the decltype for that
2144/// expression, according to the rules in C++0x [dcl.type.simple]p4
2145static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002146 if (e->isTypeDependent())
2147 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002149 // If e is an id expression or a class member access, decltype(e) is defined
2150 // as the type of the entity named by e.
2151 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2152 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2153 return VD->getType();
2154 }
2155 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2156 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2157 return FD->getType();
2158 }
2159 // If e is a function call or an invocation of an overloaded operator,
2160 // (parentheses around e are ignored), decltype(e) is defined as the
2161 // return type of that function.
2162 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2163 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002165 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002166
2167 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002168 // defined as T&, otherwise decltype(e) is defined as T.
2169 if (e->isLvalue(Context) == Expr::LV_Valid)
2170 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002172 return T;
2173}
2174
Anders Carlsson395b4752009-06-24 19:06:50 +00002175/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2176/// DecltypeType AST's. The only motivation to unique these nodes would be
2177/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002178/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002179/// on canonical type's (which are always unique).
2180QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002181 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002182 if (e->isTypeDependent()) {
2183 llvm::FoldingSetNodeID ID;
2184 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002186 void *InsertPos = 0;
2187 DependentDecltypeType *Canon
2188 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2189 if (Canon) {
2190 // We already have a "canonical" version of an equivalent, dependent
2191 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002192 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002193 QualType((DecltypeType*)Canon, 0));
2194 }
2195 else {
2196 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002197 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002198 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2199 dt = Canon;
2200 }
2201 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002202 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002203 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002204 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002205 Types.push_back(dt);
2206 return QualType(dt, 0);
2207}
2208
Reid Spencer5f016e22007-07-11 17:01:13 +00002209/// getTagDeclType - Return the unique reference to the type for the
2210/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002211QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002212 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002213 // FIXME: What is the design on getTagDeclType when it requires casting
2214 // away const? mutable?
2215 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002216}
2217
Mike Stump1eb44332009-09-09 15:08:12 +00002218/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2219/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2220/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002221CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002222 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002223}
2224
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002225/// getSignedWCharType - Return the type of "signed wchar_t".
2226/// Used when in C++, as a GCC extension.
2227QualType ASTContext::getSignedWCharType() const {
2228 // FIXME: derive from "Target" ?
2229 return WCharTy;
2230}
2231
2232/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2233/// Used when in C++, as a GCC extension.
2234QualType ASTContext::getUnsignedWCharType() const {
2235 // FIXME: derive from "Target" ?
2236 return UnsignedIntTy;
2237}
2238
Chris Lattner8b9023b2007-07-13 03:05:23 +00002239/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2240/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2241QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002242 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002243}
2244
Chris Lattnere6327742008-04-02 05:18:44 +00002245//===----------------------------------------------------------------------===//
2246// Type Operators
2247//===----------------------------------------------------------------------===//
2248
John McCall54e14c42009-10-22 22:37:11 +00002249CanQualType ASTContext::getCanonicalParamType(QualType T) {
2250 // Push qualifiers into arrays, and then discard any remaining
2251 // qualifiers.
2252 T = getCanonicalType(T);
2253 const Type *Ty = T.getTypePtr();
2254
2255 QualType Result;
2256 if (isa<ArrayType>(Ty)) {
2257 Result = getArrayDecayedType(QualType(Ty,0));
2258 } else if (isa<FunctionType>(Ty)) {
2259 Result = getPointerType(QualType(Ty, 0));
2260 } else {
2261 Result = QualType(Ty, 0);
2262 }
2263
2264 return CanQualType::CreateUnsafe(Result);
2265}
2266
Chris Lattner77c96472008-04-06 22:41:35 +00002267/// getCanonicalType - Return the canonical (structural) type corresponding to
2268/// the specified potentially non-canonical type. The non-canonical version
2269/// of a type may have many "decorated" versions of types. Decorators can
2270/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2271/// to be free of any of these, allowing two canonical types to be compared
2272/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002273CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002274 QualifierCollector Quals;
2275 const Type *Ptr = Quals.strip(T);
2276 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002277
John McCall0953e762009-09-24 19:53:00 +00002278 // The canonical internal type will be the canonical type *except*
2279 // that we push type qualifiers down through array types.
2280
2281 // If there are no new qualifiers to push down, stop here.
2282 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002283 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002284
John McCall0953e762009-09-24 19:53:00 +00002285 // If the type qualifiers are on an array type, get the canonical
2286 // type of the array with the qualifiers applied to the element
2287 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002288 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2289 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002290 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002292 // Get the canonical version of the element with the extra qualifiers on it.
2293 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002294 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002295 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002297 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002298 return CanQualType::CreateUnsafe(
2299 getConstantArrayType(NewEltTy, CAT->getSize(),
2300 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002301 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002302 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002303 return CanQualType::CreateUnsafe(
2304 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002305 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Douglas Gregor898574e2008-12-05 23:32:09 +00002307 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002308 return CanQualType::CreateUnsafe(
2309 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002310 DSAT->getSizeExpr() ?
2311 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002312 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002313 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002314 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002315
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002316 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002317 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002318 VAT->getSizeExpr() ?
2319 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002320 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002321 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002322 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002323}
2324
Chandler Carruth28e318c2009-12-29 07:16:59 +00002325QualType ASTContext::getUnqualifiedArrayType(QualType T,
2326 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002327 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002328 const ArrayType *AT = getAsArrayType(T);
2329 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002330 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002331 }
2332
Chandler Carruth28e318c2009-12-29 07:16:59 +00002333 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002334 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002335 if (Elt == UnqualElt)
2336 return T;
2337
Douglas Gregor9dadd942010-05-17 18:45:21 +00002338 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002339 return getConstantArrayType(UnqualElt, CAT->getSize(),
2340 CAT->getSizeModifier(), 0);
2341 }
2342
Douglas Gregor9dadd942010-05-17 18:45:21 +00002343 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002344 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2345 }
2346
Douglas Gregor9dadd942010-05-17 18:45:21 +00002347 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2348 return getVariableArrayType(UnqualElt,
2349 VAT->getSizeExpr() ?
2350 VAT->getSizeExpr()->Retain() : 0,
2351 VAT->getSizeModifier(),
2352 VAT->getIndexTypeCVRQualifiers(),
2353 VAT->getBracketsRange());
2354 }
2355
2356 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002357 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2358 DSAT->getSizeModifier(), 0,
2359 SourceRange());
2360}
2361
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002362/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2363/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2364/// they point to and return true. If T1 and T2 aren't pointer types
2365/// or pointer-to-member types, or if they are not similar at this
2366/// level, returns false and leaves T1 and T2 unchanged. Top-level
2367/// qualifiers on T1 and T2 are ignored. This function will typically
2368/// be called in a loop that successively "unwraps" pointer and
2369/// pointer-to-member types to compare them at each level.
2370bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2371 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2372 *T2PtrType = T2->getAs<PointerType>();
2373 if (T1PtrType && T2PtrType) {
2374 T1 = T1PtrType->getPointeeType();
2375 T2 = T2PtrType->getPointeeType();
2376 return true;
2377 }
2378
2379 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2380 *T2MPType = T2->getAs<MemberPointerType>();
2381 if (T1MPType && T2MPType &&
2382 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2383 QualType(T2MPType->getClass(), 0))) {
2384 T1 = T1MPType->getPointeeType();
2385 T2 = T2MPType->getPointeeType();
2386 return true;
2387 }
2388
2389 if (getLangOptions().ObjC1) {
2390 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2391 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2392 if (T1OPType && T2OPType) {
2393 T1 = T1OPType->getPointeeType();
2394 T2 = T2OPType->getPointeeType();
2395 return true;
2396 }
2397 }
2398
2399 // FIXME: Block pointers, too?
2400
2401 return false;
2402}
2403
John McCall80ad16f2009-11-24 18:42:40 +00002404DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2405 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2406 return TD->getDeclName();
2407
2408 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2409 if (DTN->isIdentifier()) {
2410 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2411 } else {
2412 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2413 }
2414 }
2415
John McCall0bd6feb2009-12-02 08:04:21 +00002416 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2417 assert(Storage);
2418 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002419}
2420
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002421TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2422 // If this template name refers to a template, the canonical
2423 // template name merely stores the template itself.
2424 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002425 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002426
John McCall0bd6feb2009-12-02 08:04:21 +00002427 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002429 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2430 assert(DTN && "Non-dependent template names must refer to template decls.");
2431 return DTN->CanonicalTemplateName;
2432}
2433
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002434bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2435 X = getCanonicalTemplateName(X);
2436 Y = getCanonicalTemplateName(Y);
2437 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2438}
2439
Mike Stump1eb44332009-09-09 15:08:12 +00002440TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002441ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2442 switch (Arg.getKind()) {
2443 case TemplateArgument::Null:
2444 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Douglas Gregor1275ae02009-07-28 23:00:59 +00002446 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002447 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregor1275ae02009-07-28 23:00:59 +00002449 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002450 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Douglas Gregor788cd062009-11-11 01:00:40 +00002452 case TemplateArgument::Template:
2453 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2454
Douglas Gregor1275ae02009-07-28 23:00:59 +00002455 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002456 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002457 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002458
Douglas Gregor1275ae02009-07-28 23:00:59 +00002459 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002460 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Douglas Gregor1275ae02009-07-28 23:00:59 +00002462 case TemplateArgument::Pack: {
2463 // FIXME: Allocate in ASTContext
2464 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2465 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002466 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002467 AEnd = Arg.pack_end();
2468 A != AEnd; (void)++A, ++Idx)
2469 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Douglas Gregor1275ae02009-07-28 23:00:59 +00002471 TemplateArgument Result;
2472 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2473 return Result;
2474 }
2475 }
2476
2477 // Silence GCC warning
2478 assert(false && "Unhandled template argument kind");
2479 return TemplateArgument();
2480}
2481
Douglas Gregord57959a2009-03-27 23:10:48 +00002482NestedNameSpecifier *
2483ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002484 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002485 return 0;
2486
2487 switch (NNS->getKind()) {
2488 case NestedNameSpecifier::Identifier:
2489 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002490 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002491 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2492 NNS->getAsIdentifier());
2493
2494 case NestedNameSpecifier::Namespace:
2495 // A namespace is canonical; build a nested-name-specifier with
2496 // this namespace and no prefix.
2497 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2498
2499 case NestedNameSpecifier::TypeSpec:
2500 case NestedNameSpecifier::TypeSpecWithTemplate: {
2501 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002502 return NestedNameSpecifier::Create(*this, 0,
2503 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002504 T.getTypePtr());
2505 }
2506
2507 case NestedNameSpecifier::Global:
2508 // The global specifier is canonical and unique.
2509 return NNS;
2510 }
2511
2512 // Required to silence a GCC warning
2513 return 0;
2514}
2515
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002516
2517const ArrayType *ASTContext::getAsArrayType(QualType T) {
2518 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002519 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002520 // Handle the common positive case fast.
2521 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2522 return AT;
2523 }
Mike Stump1eb44332009-09-09 15:08:12 +00002524
John McCall0953e762009-09-24 19:53:00 +00002525 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002526 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002527 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002528 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002529
John McCall0953e762009-09-24 19:53:00 +00002530 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002531 // implements C99 6.7.3p8: "If the specification of an array type includes
2532 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002534 // If we get here, we either have type qualifiers on the type, or we have
2535 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002536 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002537
John McCall0953e762009-09-24 19:53:00 +00002538 QualifierCollector Qs;
2539 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002541 // If we have a simple case, just return now.
2542 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002543 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002544 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002546 // Otherwise, we have an array and we have qualifiers on it. Push the
2547 // qualifiers into the array element type and return a new array type.
2548 // Get the canonical version of the element with the extra qualifiers on it.
2549 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002550 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002552 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2553 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2554 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002555 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002556 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2557 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2558 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002559 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002560
Mike Stump1eb44332009-09-09 15:08:12 +00002561 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002562 = dyn_cast<DependentSizedArrayType>(ATy))
2563 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002564 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002565 DSAT->getSizeExpr() ?
2566 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002567 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002568 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002569 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002571 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002572 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002573 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002574 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002575 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002576 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002577 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002578}
2579
2580
Chris Lattnere6327742008-04-02 05:18:44 +00002581/// getArrayDecayedType - Return the properly qualified result of decaying the
2582/// specified array type to a pointer. This operation is non-trivial when
2583/// handling typedefs etc. The canonical type of "T" must be an array type,
2584/// this returns a pointer to a properly qualified element of the array.
2585///
2586/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2587QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002588 // Get the element type with 'getAsArrayType' so that we don't lose any
2589 // typedefs in the element type of the array. This also handles propagation
2590 // of type qualifiers from the array type into the element type if present
2591 // (C99 6.7.3p8).
2592 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2593 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002595 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002596
2597 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002598 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002599}
2600
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002601QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002602 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002603 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2604 QT = AT->getElementType();
2605 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002606}
2607
Anders Carlssonfbbce492009-09-25 01:23:32 +00002608QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2609 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Anders Carlssonfbbce492009-09-25 01:23:32 +00002611 if (const ArrayType *AT = getAsArrayType(ElemTy))
2612 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Anders Carlsson6183a992008-12-21 03:44:36 +00002614 return ElemTy;
2615}
2616
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002617/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002618uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002619ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2620 uint64_t ElementCount = 1;
2621 do {
2622 ElementCount *= CA->getSize().getZExtValue();
2623 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2624 } while (CA);
2625 return ElementCount;
2626}
2627
Reid Spencer5f016e22007-07-11 17:01:13 +00002628/// getFloatingRank - Return a relative rank for floating point types.
2629/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002630static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002631 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002633
John McCall183700f2009-09-21 23:43:11 +00002634 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2635 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002636 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 case BuiltinType::Float: return FloatRank;
2638 case BuiltinType::Double: return DoubleRank;
2639 case BuiltinType::LongDouble: return LongDoubleRank;
2640 }
2641}
2642
Mike Stump1eb44332009-09-09 15:08:12 +00002643/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2644/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002645/// 'typeDomain' is a real floating point or complex type.
2646/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002647QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2648 QualType Domain) const {
2649 FloatingRank EltRank = getFloatingRank(Size);
2650 if (Domain->isComplexType()) {
2651 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002652 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002653 case FloatRank: return FloatComplexTy;
2654 case DoubleRank: return DoubleComplexTy;
2655 case LongDoubleRank: return LongDoubleComplexTy;
2656 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 }
Chris Lattner1361b112008-04-06 23:58:54 +00002658
2659 assert(Domain->isRealFloatingType() && "Unknown domain!");
2660 switch (EltRank) {
2661 default: assert(0 && "getFloatingRank(): illegal value for rank");
2662 case FloatRank: return FloatTy;
2663 case DoubleRank: return DoubleTy;
2664 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002665 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002666}
2667
Chris Lattner7cfeb082008-04-06 23:55:33 +00002668/// getFloatingTypeOrder - Compare the rank of the two specified floating
2669/// point types, ignoring the domain of the type (i.e. 'double' ==
2670/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002671/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002672int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2673 FloatingRank LHSR = getFloatingRank(LHS);
2674 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Chris Lattnera75cea32008-04-06 23:38:49 +00002676 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002677 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002678 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002679 return 1;
2680 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681}
2682
Chris Lattnerf52ab252008-04-06 22:59:24 +00002683/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2684/// routine will assert if passed a built-in type that isn't an integer or enum,
2685/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002686unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002687 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002688 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002689 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002690
Eli Friedmana3426752009-07-05 23:44:27 +00002691 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2692 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2693
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002694 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2695 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2696
2697 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2698 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2699
Chris Lattnerf52ab252008-04-06 22:59:24 +00002700 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002701 default: assert(0 && "getIntegerRank(): not a built-in integer");
2702 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002703 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002704 case BuiltinType::Char_S:
2705 case BuiltinType::Char_U:
2706 case BuiltinType::SChar:
2707 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002708 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002709 case BuiltinType::Short:
2710 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002711 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002712 case BuiltinType::Int:
2713 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002714 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002715 case BuiltinType::Long:
2716 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002717 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002718 case BuiltinType::LongLong:
2719 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002720 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002721 case BuiltinType::Int128:
2722 case BuiltinType::UInt128:
2723 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002724 }
2725}
2726
Eli Friedman04e83572009-08-20 04:21:42 +00002727/// \brief Whether this is a promotable bitfield reference according
2728/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2729///
2730/// \returns the type this bit-field will promote to, or NULL if no
2731/// promotion occurs.
2732QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002733 if (E->isTypeDependent() || E->isValueDependent())
2734 return QualType();
2735
Eli Friedman04e83572009-08-20 04:21:42 +00002736 FieldDecl *Field = E->getBitField();
2737 if (!Field)
2738 return QualType();
2739
2740 QualType FT = Field->getType();
2741
2742 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2743 uint64_t BitWidth = BitWidthAP.getZExtValue();
2744 uint64_t IntSize = getTypeSize(IntTy);
2745 // GCC extension compatibility: if the bit-field size is less than or equal
2746 // to the size of int, it gets promoted no matter what its type is.
2747 // For instance, unsigned long bf : 4 gets promoted to signed int.
2748 if (BitWidth < IntSize)
2749 return IntTy;
2750
2751 if (BitWidth == IntSize)
2752 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2753
2754 // Types bigger than int are not subject to promotions, and therefore act
2755 // like the base type.
2756 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2757 // is ridiculous.
2758 return QualType();
2759}
2760
Eli Friedmana95d7572009-08-19 07:44:53 +00002761/// getPromotedIntegerType - Returns the type that Promotable will
2762/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2763/// integer type.
2764QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2765 assert(!Promotable.isNull());
2766 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002767 if (const EnumType *ET = Promotable->getAs<EnumType>())
2768 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002769 if (Promotable->isSignedIntegerType())
2770 return IntTy;
2771 uint64_t PromotableSize = getTypeSize(Promotable);
2772 uint64_t IntSize = getTypeSize(IntTy);
2773 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2774 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2775}
2776
Mike Stump1eb44332009-09-09 15:08:12 +00002777/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002778/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002779/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002780int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002781 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2782 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002783 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Chris Lattnerf52ab252008-04-06 22:59:24 +00002785 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2786 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Chris Lattner7cfeb082008-04-06 23:55:33 +00002788 unsigned LHSRank = getIntegerRank(LHSC);
2789 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Chris Lattner7cfeb082008-04-06 23:55:33 +00002791 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2792 if (LHSRank == RHSRank) return 0;
2793 return LHSRank > RHSRank ? 1 : -1;
2794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Chris Lattner7cfeb082008-04-06 23:55:33 +00002796 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2797 if (LHSUnsigned) {
2798 // If the unsigned [LHS] type is larger, return it.
2799 if (LHSRank >= RHSRank)
2800 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattner7cfeb082008-04-06 23:55:33 +00002802 // If the signed type can represent all values of the unsigned type, it
2803 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002804 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002805 return -1;
2806 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002807
Chris Lattner7cfeb082008-04-06 23:55:33 +00002808 // If the unsigned [RHS] type is larger, return it.
2809 if (RHSRank >= LHSRank)
2810 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Chris Lattner7cfeb082008-04-06 23:55:33 +00002812 // If the signed type can represent all values of the unsigned type, it
2813 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002814 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002815 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002817
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002818static RecordDecl *
2819CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2820 SourceLocation L, IdentifierInfo *Id) {
2821 if (Ctx.getLangOptions().CPlusPlus)
2822 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2823 else
2824 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2825}
2826
Mike Stump1eb44332009-09-09 15:08:12 +00002827// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002828QualType ASTContext::getCFConstantStringType() {
2829 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002830 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002831 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002832 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002833 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002834
Anders Carlssonf06273f2007-11-19 00:25:30 +00002835 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Anders Carlsson71993dd2007-08-17 05:31:46 +00002837 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002838 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002839 // int flags;
2840 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002841 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002842 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002843 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002844 FieldTypes[3] = LongTy;
2845
Anders Carlsson71993dd2007-08-17 05:31:46 +00002846 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002847 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002848 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002849 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002850 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002851 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002852 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002853 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002854 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002855 }
2856
Douglas Gregor838db382010-02-11 01:19:42 +00002857 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002858 }
Mike Stump1eb44332009-09-09 15:08:12 +00002859
Anders Carlsson71993dd2007-08-17 05:31:46 +00002860 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002861}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002862
Douglas Gregor319ac892009-04-23 22:29:11 +00002863void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002864 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002865 assert(Rec && "Invalid CFConstantStringType");
2866 CFConstantStringTypeDecl = Rec->getDecl();
2867}
2868
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002869// getNSConstantStringType - Return the type used for constant NSStrings.
2870QualType ASTContext::getNSConstantStringType() {
2871 if (!NSConstantStringTypeDecl) {
2872 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002873 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002874 &Idents.get("__builtin_NSString"));
2875 NSConstantStringTypeDecl->startDefinition();
2876
2877 QualType FieldTypes[3];
2878
2879 // const int *isa;
2880 FieldTypes[0] = getPointerType(IntTy.withConst());
2881 // const char *str;
2882 FieldTypes[1] = getPointerType(CharTy.withConst());
2883 // unsigned int length;
2884 FieldTypes[2] = UnsignedIntTy;
2885
2886 // Create fields
2887 for (unsigned i = 0; i < 3; ++i) {
2888 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2889 SourceLocation(), 0,
2890 FieldTypes[i], /*TInfo=*/0,
2891 /*BitWidth=*/0,
2892 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002893 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002894 NSConstantStringTypeDecl->addDecl(Field);
2895 }
2896
2897 NSConstantStringTypeDecl->completeDefinition();
2898 }
2899
2900 return getTagDeclType(NSConstantStringTypeDecl);
2901}
2902
2903void ASTContext::setNSConstantStringType(QualType T) {
2904 const RecordType *Rec = T->getAs<RecordType>();
2905 assert(Rec && "Invalid NSConstantStringType");
2906 NSConstantStringTypeDecl = Rec->getDecl();
2907}
2908
Mike Stump1eb44332009-09-09 15:08:12 +00002909QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002910 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002911 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002912 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002913 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002914 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002916 QualType FieldTypes[] = {
2917 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002918 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002919 getPointerType(UnsignedLongTy),
2920 getConstantArrayType(UnsignedLongTy,
2921 llvm::APInt(32, 5), ArrayType::Normal, 0)
2922 };
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Douglas Gregor44b43212008-12-11 16:49:14 +00002924 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002925 FieldDecl *Field = FieldDecl::Create(*this,
2926 ObjCFastEnumerationStateTypeDecl,
2927 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002928 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002929 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002930 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002931 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002932 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002933 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00002934 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00002935 if (CXXRecordDecl *CXXRD =
2936 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00002937 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Douglas Gregor838db382010-02-11 01:19:42 +00002939 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002940 }
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002942 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2943}
2944
Mike Stumpadaaad32009-10-20 02:12:22 +00002945QualType ASTContext::getBlockDescriptorType() {
2946 if (BlockDescriptorType)
2947 return getTagDeclType(BlockDescriptorType);
2948
2949 RecordDecl *T;
2950 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002951 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002952 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00002953 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002954
2955 QualType FieldTypes[] = {
2956 UnsignedLongTy,
2957 UnsignedLongTy,
2958 };
2959
2960 const char *FieldNames[] = {
2961 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002962 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002963 };
2964
2965 for (size_t i = 0; i < 2; ++i) {
2966 FieldDecl *Field = FieldDecl::Create(*this,
2967 T,
2968 SourceLocation(),
2969 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002970 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002971 /*BitWidth=*/0,
2972 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002973 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00002974 T->addDecl(Field);
2975 }
2976
Douglas Gregor838db382010-02-11 01:19:42 +00002977 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002978
2979 BlockDescriptorType = T;
2980
2981 return getTagDeclType(BlockDescriptorType);
2982}
2983
2984void ASTContext::setBlockDescriptorType(QualType T) {
2985 const RecordType *Rec = T->getAs<RecordType>();
2986 assert(Rec && "Invalid BlockDescriptorType");
2987 BlockDescriptorType = Rec->getDecl();
2988}
2989
Mike Stump083c25e2009-10-22 00:49:09 +00002990QualType ASTContext::getBlockDescriptorExtendedType() {
2991 if (BlockDescriptorExtendedType)
2992 return getTagDeclType(BlockDescriptorExtendedType);
2993
2994 RecordDecl *T;
2995 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002996 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002997 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00002998 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00002999
3000 QualType FieldTypes[] = {
3001 UnsignedLongTy,
3002 UnsignedLongTy,
3003 getPointerType(VoidPtrTy),
3004 getPointerType(VoidPtrTy)
3005 };
3006
3007 const char *FieldNames[] = {
3008 "reserved",
3009 "Size",
3010 "CopyFuncPtr",
3011 "DestroyFuncPtr"
3012 };
3013
3014 for (size_t i = 0; i < 4; ++i) {
3015 FieldDecl *Field = FieldDecl::Create(*this,
3016 T,
3017 SourceLocation(),
3018 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003019 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003020 /*BitWidth=*/0,
3021 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003022 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003023 T->addDecl(Field);
3024 }
3025
Douglas Gregor838db382010-02-11 01:19:42 +00003026 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003027
3028 BlockDescriptorExtendedType = T;
3029
3030 return getTagDeclType(BlockDescriptorExtendedType);
3031}
3032
3033void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3034 const RecordType *Rec = T->getAs<RecordType>();
3035 assert(Rec && "Invalid BlockDescriptorType");
3036 BlockDescriptorExtendedType = Rec->getDecl();
3037}
3038
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003039bool ASTContext::BlockRequiresCopying(QualType Ty) {
3040 if (Ty->isBlockPointerType())
3041 return true;
3042 if (isObjCNSObjectType(Ty))
3043 return true;
3044 if (Ty->isObjCObjectPointerType())
3045 return true;
3046 return false;
3047}
3048
3049QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3050 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003051 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003052 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003053 // unsigned int __flags;
3054 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003055 // void *__copy_helper; // as needed
3056 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003057 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003058 // } *
3059
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003060 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3061
3062 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003063 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003064 llvm::SmallString<36> Name;
3065 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3066 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003067 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003068 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003069 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003070 T->startDefinition();
3071 QualType Int32Ty = IntTy;
3072 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3073 QualType FieldTypes[] = {
3074 getPointerType(VoidPtrTy),
3075 getPointerType(getTagDeclType(T)),
3076 Int32Ty,
3077 Int32Ty,
3078 getPointerType(VoidPtrTy),
3079 getPointerType(VoidPtrTy),
3080 Ty
3081 };
3082
3083 const char *FieldNames[] = {
3084 "__isa",
3085 "__forwarding",
3086 "__flags",
3087 "__size",
3088 "__copy_helper",
3089 "__destroy_helper",
3090 DeclName,
3091 };
3092
3093 for (size_t i = 0; i < 7; ++i) {
3094 if (!HasCopyAndDispose && i >=4 && i <= 5)
3095 continue;
3096 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3097 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003098 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003099 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003100 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003101 T->addDecl(Field);
3102 }
3103
Douglas Gregor838db382010-02-11 01:19:42 +00003104 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003105
3106 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003107}
3108
3109
3110QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003111 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003112 llvm::SmallVectorImpl<const Expr *> &Layout) {
3113
Mike Stumpadaaad32009-10-20 02:12:22 +00003114 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003115 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003116 llvm::SmallString<36> Name;
3117 llvm::raw_svector_ostream(Name) << "__block_literal_"
3118 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003119 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003120 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003121 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003122 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003123 QualType FieldTypes[] = {
3124 getPointerType(VoidPtrTy),
3125 IntTy,
3126 IntTy,
3127 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003128 (BlockHasCopyDispose ?
3129 getPointerType(getBlockDescriptorExtendedType()) :
3130 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003131 };
3132
3133 const char *FieldNames[] = {
3134 "__isa",
3135 "__flags",
3136 "__reserved",
3137 "__FuncPtr",
3138 "__descriptor"
3139 };
3140
3141 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003142 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003143 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003144 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003145 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003146 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003147 T->addDecl(Field);
3148 }
3149
John McCallea1471e2010-05-20 01:18:31 +00003150 for (unsigned i = 0; i < Layout.size(); ++i) {
3151 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003152
John McCallea1471e2010-05-20 01:18:31 +00003153 QualType FieldType = E->getType();
3154 IdentifierInfo *FieldName = 0;
3155 if (isa<CXXThisExpr>(E)) {
3156 FieldName = &Idents.get("this");
3157 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3158 const ValueDecl *D = BDRE->getDecl();
3159 FieldName = D->getIdentifier();
3160 if (BDRE->isByRef())
3161 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3162 } else {
3163 // Padding.
3164 assert(isa<ConstantArrayType>(FieldType) &&
3165 isa<DeclRefExpr>(E) &&
3166 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3167 "doesn't match characteristics of padding decl");
3168 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003169
3170 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003171 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003172 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003173 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003174 T->addDecl(Field);
3175 }
3176
Douglas Gregor838db382010-02-11 01:19:42 +00003177 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003178
3179 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003180}
3181
Douglas Gregor319ac892009-04-23 22:29:11 +00003182void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003183 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003184 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3185 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3186}
3187
Anders Carlssone8c49532007-10-29 06:33:42 +00003188// This returns true if a type has been typedefed to BOOL:
3189// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003190static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003191 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003192 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3193 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003195 return false;
3196}
3197
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003198/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003199/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003200CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003201 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003203 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003204 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003205 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003206 // Treat arrays as pointers, since that's how they're passed in.
3207 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003208 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003209 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003210}
3211
3212static inline
3213std::string charUnitsToString(const CharUnits &CU) {
3214 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003215}
3216
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003217/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003218/// declaration.
3219void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3220 std::string& S) {
3221 const BlockDecl *Decl = Expr->getBlockDecl();
3222 QualType BlockTy =
3223 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3224 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003225 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003226 // Compute size of all parameters.
3227 // Start with computing size of a pointer in number of bytes.
3228 // FIXME: There might(should) be a better way of doing this computation!
3229 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003230 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3231 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003232 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003233 E = Decl->param_end(); PI != E; ++PI) {
3234 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003235 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003236 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003237 ParmOffset += sz;
3238 }
3239 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003240 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003241 // Block pointer and offset.
3242 S += "@?0";
3243 ParmOffset = PtrSize;
3244
3245 // Argument types.
3246 ParmOffset = PtrSize;
3247 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3248 Decl->param_end(); PI != E; ++PI) {
3249 ParmVarDecl *PVDecl = *PI;
3250 QualType PType = PVDecl->getOriginalType();
3251 if (const ArrayType *AT =
3252 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3253 // Use array's original type only if it has known number of
3254 // elements.
3255 if (!isa<ConstantArrayType>(AT))
3256 PType = PVDecl->getType();
3257 } else if (PType->isFunctionType())
3258 PType = PVDecl->getType();
3259 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003260 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003261 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003262 }
3263}
3264
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003265/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003266/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003267void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003268 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003269 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003270 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003271 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003272 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003273 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003274 // Compute size of all parameters.
3275 // Start with computing size of a pointer in number of bytes.
3276 // FIXME: There might(should) be a better way of doing this computation!
3277 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003278 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003279 // The first two arguments (self and _cmd) are pointers; account for
3280 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003281 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003282 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003283 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003284 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003285 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003286 assert (sz.isPositive() &&
3287 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003288 ParmOffset += sz;
3289 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003290 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003291 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003292 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003294 // Argument types.
3295 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003296 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003297 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003298 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003299 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003300 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003301 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3302 // Use array's original type only if it has known number of
3303 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003304 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003305 PType = PVDecl->getType();
3306 } else if (PType->isFunctionType())
3307 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003308 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003309 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003310 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003311 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003312 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003313 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003314 }
3315}
3316
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003317/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003318/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003319/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3320/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003321/// Property attributes are stored as a comma-delimited C string. The simple
3322/// attributes readonly and bycopy are encoded as single characters. The
3323/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3324/// encoded as single characters, followed by an identifier. Property types
3325/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003326/// these attributes are defined by the following enumeration:
3327/// @code
3328/// enum PropertyAttributes {
3329/// kPropertyReadOnly = 'R', // property is read-only.
3330/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3331/// kPropertyByref = '&', // property is a reference to the value last assigned
3332/// kPropertyDynamic = 'D', // property is dynamic
3333/// kPropertyGetter = 'G', // followed by getter selector name
3334/// kPropertySetter = 'S', // followed by setter selector name
3335/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3336/// kPropertyType = 't' // followed by old-style type encoding.
3337/// kPropertyWeak = 'W' // 'weak' property
3338/// kPropertyStrong = 'P' // property GC'able
3339/// kPropertyNonAtomic = 'N' // property non-atomic
3340/// };
3341/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003342void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003343 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003344 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003345 // Collect information from the property implementation decl(s).
3346 bool Dynamic = false;
3347 ObjCPropertyImplDecl *SynthesizePID = 0;
3348
3349 // FIXME: Duplicated code due to poor abstraction.
3350 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003351 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003352 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3353 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003354 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003355 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003356 ObjCPropertyImplDecl *PID = *i;
3357 if (PID->getPropertyDecl() == PD) {
3358 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3359 Dynamic = true;
3360 } else {
3361 SynthesizePID = PID;
3362 }
3363 }
3364 }
3365 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003366 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003367 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003368 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003369 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003370 ObjCPropertyImplDecl *PID = *i;
3371 if (PID->getPropertyDecl() == PD) {
3372 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3373 Dynamic = true;
3374 } else {
3375 SynthesizePID = PID;
3376 }
3377 }
Mike Stump1eb44332009-09-09 15:08:12 +00003378 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003379 }
3380 }
3381
3382 // FIXME: This is not very efficient.
3383 S = "T";
3384
3385 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003386 // GCC has some special rules regarding encoding of properties which
3387 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003388 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003389 true /* outermost type */,
3390 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003391
3392 if (PD->isReadOnly()) {
3393 S += ",R";
3394 } else {
3395 switch (PD->getSetterKind()) {
3396 case ObjCPropertyDecl::Assign: break;
3397 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003398 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003399 }
3400 }
3401
3402 // It really isn't clear at all what this means, since properties
3403 // are "dynamic by default".
3404 if (Dynamic)
3405 S += ",D";
3406
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003407 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3408 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003410 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3411 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003412 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003413 }
3414
3415 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3416 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003417 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003418 }
3419
3420 if (SynthesizePID) {
3421 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3422 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003423 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003424 }
3425
3426 // FIXME: OBJCGC: weak & strong
3427}
3428
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003429/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003430/// Another legacy compatibility encoding: 32-bit longs are encoded as
3431/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003432/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3433///
3434void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003435 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003436 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003437 if (BT->getKind() == BuiltinType::ULong &&
3438 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003439 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003440 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003441 if (BT->getKind() == BuiltinType::Long &&
3442 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003443 PointeeTy = IntTy;
3444 }
3445 }
3446}
3447
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003448void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003449 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003450 // We follow the behavior of gcc, expanding structures which are
3451 // directly pointed to, and expanding embedded structures. Note that
3452 // these rules are sufficient to prevent recursive encoding of the
3453 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003454 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003455 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003456}
3457
David Chisnall64fd7e82010-06-04 01:10:52 +00003458static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3459 switch (T->getAs<BuiltinType>()->getKind()) {
3460 default: assert(0 && "Unhandled builtin type kind");
3461 case BuiltinType::Void: return 'v';
3462 case BuiltinType::Bool: return 'B';
3463 case BuiltinType::Char_U:
3464 case BuiltinType::UChar: return 'C';
3465 case BuiltinType::UShort: return 'S';
3466 case BuiltinType::UInt: return 'I';
3467 case BuiltinType::ULong:
3468 return
3469 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3470 case BuiltinType::UInt128: return 'T';
3471 case BuiltinType::ULongLong: return 'Q';
3472 case BuiltinType::Char_S:
3473 case BuiltinType::SChar: return 'c';
3474 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003475 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003476 case BuiltinType::Int: return 'i';
3477 case BuiltinType::Long:
3478 return
3479 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3480 case BuiltinType::LongLong: return 'q';
3481 case BuiltinType::Int128: return 't';
3482 case BuiltinType::Float: return 'f';
3483 case BuiltinType::Double: return 'd';
3484 case BuiltinType::LongDouble: return 'd';
3485 }
3486}
3487
Mike Stump1eb44332009-09-09 15:08:12 +00003488static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003489 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003490 const Expr *E = FD->getBitWidth();
3491 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3492 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003493 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003494 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3495 // The GNU runtime requires more information; bitfields are encoded as b,
3496 // then the offset (in bits) of the first element, then the type of the
3497 // bitfield, then the size in bits. For example, in this structure:
3498 //
3499 // struct
3500 // {
3501 // int integer;
3502 // int flags:2;
3503 // };
3504 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3505 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3506 // information is not especially sensible, but we're stuck with it for
3507 // compatibility with GCC, although providing it breaks anything that
3508 // actually uses runtime introspection and wants to work on both runtimes...
3509 if (!Ctx->getLangOptions().NeXTRuntime) {
3510 const RecordDecl *RD = FD->getParent();
3511 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3512 // FIXME: This same linear search is also used in ExprConstant - it might
3513 // be better if the FieldDecl stored its offset. We'd be increasing the
3514 // size of the object slightly, but saving some time every time it is used.
3515 unsigned i = 0;
3516 for (RecordDecl::field_iterator Field = RD->field_begin(),
3517 FieldEnd = RD->field_end();
3518 Field != FieldEnd; (void)++Field, ++i) {
3519 if (*Field == FD)
3520 break;
3521 }
3522 S += llvm::utostr(RL.getFieldOffset(i));
3523 S += ObjCEncodingForPrimitiveKind(Context, T);
3524 }
3525 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003526 S += llvm::utostr(N);
3527}
3528
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003529// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003530void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3531 bool ExpandPointedToStructures,
3532 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003533 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003534 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003535 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003536 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003537 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003538 return EncodeBitField(this, S, T, FD);
3539 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003540 return;
3541 }
Mike Stump1eb44332009-09-09 15:08:12 +00003542
John McCall183700f2009-09-21 23:43:11 +00003543 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003544 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003545 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003546 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003547 return;
3548 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003549
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003550 // encoding for pointer or r3eference types.
3551 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003552 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003553 if (PT->isObjCSelType()) {
3554 S += ':';
3555 return;
3556 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003557 PointeeTy = PT->getPointeeType();
3558 }
3559 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3560 PointeeTy = RT->getPointeeType();
3561 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003562 bool isReadOnly = false;
3563 // For historical/compatibility reasons, the read-only qualifier of the
3564 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3565 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003566 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003567 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003568 if (OutermostType && T.isConstQualified()) {
3569 isReadOnly = true;
3570 S += 'r';
3571 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003572 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003573 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003574 while (P->getAs<PointerType>())
3575 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003576 if (P.isConstQualified()) {
3577 isReadOnly = true;
3578 S += 'r';
3579 }
3580 }
3581 if (isReadOnly) {
3582 // Another legacy compatibility encoding. Some ObjC qualifier and type
3583 // combinations need to be rearranged.
3584 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003585 if (llvm::StringRef(S).endswith("nr"))
3586 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003587 }
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003589 if (PointeeTy->isCharType()) {
3590 // char pointer types should be encoded as '*' unless it is a
3591 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003592 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003593 S += '*';
3594 return;
3595 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003596 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003597 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3598 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3599 S += '#';
3600 return;
3601 }
3602 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3603 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3604 S += '@';
3605 return;
3606 }
3607 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003608 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003609 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003610 getLegacyIntegralTypeEncoding(PointeeTy);
3611
Mike Stump1eb44332009-09-09 15:08:12 +00003612 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003613 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003614 return;
3615 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003616
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003617 if (const ArrayType *AT =
3618 // Ignore type qualifiers etc.
3619 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003620 if (isa<IncompleteArrayType>(AT)) {
3621 // Incomplete arrays are encoded as a pointer to the array element.
3622 S += '^';
3623
Mike Stump1eb44332009-09-09 15:08:12 +00003624 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003625 false, ExpandStructures, FD);
3626 } else {
3627 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Anders Carlsson559a8332009-02-22 01:38:57 +00003629 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3630 S += llvm::utostr(CAT->getSize().getZExtValue());
3631 else {
3632 //Variable length arrays are encoded as a regular array with 0 elements.
3633 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3634 S += '0';
3635 }
Mike Stump1eb44332009-09-09 15:08:12 +00003636
3637 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003638 false, ExpandStructures, FD);
3639 S += ']';
3640 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003641 return;
3642 }
Mike Stump1eb44332009-09-09 15:08:12 +00003643
John McCall183700f2009-09-21 23:43:11 +00003644 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003645 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003646 return;
3647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Ted Kremenek6217b802009-07-29 21:53:49 +00003649 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003650 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003651 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003652 // Anonymous structures print as '?'
3653 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3654 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003655 if (ClassTemplateSpecializationDecl *Spec
3656 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3657 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3658 std::string TemplateArgsStr
3659 = TemplateSpecializationType::PrintTemplateArgumentList(
3660 TemplateArgs.getFlatArgumentList(),
3661 TemplateArgs.flat_size(),
3662 (*this).PrintingPolicy);
3663
3664 S += TemplateArgsStr;
3665 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003666 } else {
3667 S += '?';
3668 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003669 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003670 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003671 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3672 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003673 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003674 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003675 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003676 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003677 S += '"';
3678 }
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003680 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003681 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003682 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003683 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003684 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003685 QualType qt = Field->getType();
3686 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003687 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003688 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003689 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003690 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003691 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003692 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003693 return;
3694 }
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003696 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003697 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003698 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003699 else
3700 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003701 return;
3702 }
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003704 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003705 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003706 return;
3707 }
Mike Stump1eb44332009-09-09 15:08:12 +00003708
John McCallc12c5bb2010-05-15 11:32:37 +00003709 // Ignore protocol qualifiers when mangling at this level.
3710 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3711 T = OT->getBaseType();
3712
John McCall0953e762009-09-24 19:53:00 +00003713 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003714 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003715 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003716 S += '{';
3717 const IdentifierInfo *II = OI->getIdentifier();
3718 S += II->getName();
3719 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003720 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003721 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003722 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003723 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003724 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003725 RecFields[i]);
3726 else
Mike Stump1eb44332009-09-09 15:08:12 +00003727 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003728 FD);
3729 }
3730 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003731 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003732 }
Mike Stump1eb44332009-09-09 15:08:12 +00003733
John McCall183700f2009-09-21 23:43:11 +00003734 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003735 if (OPT->isObjCIdType()) {
3736 S += '@';
3737 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003738 }
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Steve Naroff27d20a22009-10-28 22:03:49 +00003740 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3741 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3742 // Since this is a binary compatibility issue, need to consult with runtime
3743 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003744 S += '#';
3745 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003746 }
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003748 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003749 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003750 ExpandPointedToStructures,
3751 ExpandStructures, FD);
3752 if (FD || EncodingProperty) {
3753 // Note that we do extended encoding of protocol qualifer list
3754 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003755 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003756 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3757 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003758 S += '<';
3759 S += (*I)->getNameAsString();
3760 S += '>';
3761 }
3762 S += '"';
3763 }
3764 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003767 QualType PointeeTy = OPT->getPointeeType();
3768 if (!EncodingProperty &&
3769 isa<TypedefType>(PointeeTy.getTypePtr())) {
3770 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003771 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003772 // {...};
3773 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003774 getObjCEncodingForTypeImpl(PointeeTy, S,
3775 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003776 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003777 return;
3778 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003779
3780 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003781 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003782 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003783 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003784 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3785 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003786 S += '<';
3787 S += (*I)->getNameAsString();
3788 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003789 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003790 S += '"';
3791 }
3792 return;
3793 }
Mike Stump1eb44332009-09-09 15:08:12 +00003794
John McCall532ec7b2010-05-17 23:56:34 +00003795 // gcc just blithely ignores member pointers.
3796 // TODO: maybe there should be a mangling for these
3797 if (T->getAs<MemberPointerType>())
3798 return;
3799
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003800 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003801}
3802
Mike Stump1eb44332009-09-09 15:08:12 +00003803void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003804 std::string& S) const {
3805 if (QT & Decl::OBJC_TQ_In)
3806 S += 'n';
3807 if (QT & Decl::OBJC_TQ_Inout)
3808 S += 'N';
3809 if (QT & Decl::OBJC_TQ_Out)
3810 S += 'o';
3811 if (QT & Decl::OBJC_TQ_Bycopy)
3812 S += 'O';
3813 if (QT & Decl::OBJC_TQ_Byref)
3814 S += 'R';
3815 if (QT & Decl::OBJC_TQ_Oneway)
3816 S += 'V';
3817}
3818
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003819void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003820 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003822 BuiltinVaListType = T;
3823}
3824
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003825void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003826 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003827}
3828
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003829void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003830 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003831}
3832
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003833void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003834 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003835}
3836
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003837void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003838 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003839}
3840
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003841void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003842 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003843 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003845 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003846}
3847
John McCall0bd6feb2009-12-02 08:04:21 +00003848/// \brief Retrieve the template name that corresponds to a non-empty
3849/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003850TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3851 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003852 unsigned size = End - Begin;
3853 assert(size > 1 && "set is not overloaded!");
3854
3855 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3856 size * sizeof(FunctionTemplateDecl*));
3857 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3858
3859 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003860 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003861 NamedDecl *D = *I;
3862 assert(isa<FunctionTemplateDecl>(D) ||
3863 (isa<UsingShadowDecl>(D) &&
3864 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3865 *Storage++ = D;
3866 }
3867
3868 return TemplateName(OT);
3869}
3870
Douglas Gregor7532dc62009-03-30 22:58:21 +00003871/// \brief Retrieve the template name that represents a qualified
3872/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003873TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003874 bool TemplateKeyword,
3875 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003876 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003877 llvm::FoldingSetNodeID ID;
3878 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3879
3880 void *InsertPos = 0;
3881 QualifiedTemplateName *QTN =
3882 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3883 if (!QTN) {
3884 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3885 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3886 }
3887
3888 return TemplateName(QTN);
3889}
3890
3891/// \brief Retrieve the template name that represents a dependent
3892/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003893TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003894 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003895 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003896 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003897
3898 llvm::FoldingSetNodeID ID;
3899 DependentTemplateName::Profile(ID, NNS, Name);
3900
3901 void *InsertPos = 0;
3902 DependentTemplateName *QTN =
3903 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3904
3905 if (QTN)
3906 return TemplateName(QTN);
3907
3908 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3909 if (CanonNNS == NNS) {
3910 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3911 } else {
3912 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3913 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003914 DependentTemplateName *CheckQTN =
3915 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3916 assert(!CheckQTN && "Dependent type name canonicalization broken");
3917 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003918 }
3919
3920 DependentTemplateNames.InsertNode(QTN, InsertPos);
3921 return TemplateName(QTN);
3922}
3923
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003924/// \brief Retrieve the template name that represents a dependent
3925/// template name such as \c MetaFun::template operator+.
3926TemplateName
3927ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3928 OverloadedOperatorKind Operator) {
3929 assert((!NNS || NNS->isDependent()) &&
3930 "Nested name specifier must be dependent");
3931
3932 llvm::FoldingSetNodeID ID;
3933 DependentTemplateName::Profile(ID, NNS, Operator);
3934
3935 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003936 DependentTemplateName *QTN
3937 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003938
3939 if (QTN)
3940 return TemplateName(QTN);
3941
3942 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3943 if (CanonNNS == NNS) {
3944 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3945 } else {
3946 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3947 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003948
3949 DependentTemplateName *CheckQTN
3950 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3951 assert(!CheckQTN && "Dependent template name canonicalization broken");
3952 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003953 }
3954
3955 DependentTemplateNames.InsertNode(QTN, InsertPos);
3956 return TemplateName(QTN);
3957}
3958
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003959/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003960/// TargetInfo, produce the corresponding type. The unsigned @p Type
3961/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003962CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003963 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003964 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003965 case TargetInfo::SignedShort: return ShortTy;
3966 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3967 case TargetInfo::SignedInt: return IntTy;
3968 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3969 case TargetInfo::SignedLong: return LongTy;
3970 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3971 case TargetInfo::SignedLongLong: return LongLongTy;
3972 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3973 }
3974
3975 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003976 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003977}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003978
3979//===----------------------------------------------------------------------===//
3980// Type Predicates.
3981//===----------------------------------------------------------------------===//
3982
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003983/// isObjCNSObjectType - Return true if this is an NSObject object using
3984/// NSObject attribute on a c-style pointer type.
3985/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003986/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003987///
3988bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3989 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3990 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003991 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003992 return true;
3993 }
Mike Stump1eb44332009-09-09 15:08:12 +00003994 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003995}
3996
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003997/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3998/// garbage collection attribute.
3999///
John McCall0953e762009-09-24 19:53:00 +00004000Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4001 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004002 if (getLangOptions().ObjC1 &&
4003 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004004 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004005 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004006 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004007 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004008 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004009 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004010 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004011 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004012 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004013 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004014 // Non-pointers have none gc'able attribute regardless of the attribute
4015 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004016 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004017 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004018 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004019 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004020}
4021
Chris Lattner6ac46a42008-04-07 06:51:04 +00004022//===----------------------------------------------------------------------===//
4023// Type Compatibility Testing
4024//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004025
Mike Stump1eb44332009-09-09 15:08:12 +00004026/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004027/// compatible.
4028static bool areCompatVectorTypes(const VectorType *LHS,
4029 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004030 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004031 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004032 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004033}
4034
Steve Naroff4084c302009-07-23 01:01:38 +00004035//===----------------------------------------------------------------------===//
4036// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4037//===----------------------------------------------------------------------===//
4038
4039/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4040/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004041bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4042 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004043 if (lProto == rProto)
4044 return true;
4045 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4046 E = rProto->protocol_end(); PI != E; ++PI)
4047 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4048 return true;
4049 return false;
4050}
4051
Steve Naroff4084c302009-07-23 01:01:38 +00004052/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4053/// return true if lhs's protocols conform to rhs's protocol; false
4054/// otherwise.
4055bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4056 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4057 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4058 return false;
4059}
4060
4061/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4062/// ObjCQualifiedIDType.
4063bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4064 bool compare) {
4065 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004066 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004067 lhs->isObjCIdType() || lhs->isObjCClassType())
4068 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004069 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004070 rhs->isObjCIdType() || rhs->isObjCClassType())
4071 return true;
4072
4073 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004074 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004075
Steve Naroff4084c302009-07-23 01:01:38 +00004076 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Steve Naroff4084c302009-07-23 01:01:38 +00004078 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004079 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004080 // make sure we check the class hierarchy.
4081 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4082 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4083 E = lhsQID->qual_end(); I != E; ++I) {
4084 // when comparing an id<P> on lhs with a static type on rhs,
4085 // see if static class implements all of id's protocols, directly or
4086 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004087 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004088 return false;
4089 }
4090 }
4091 // If there are no qualifiers and no interface, we have an 'id'.
4092 return true;
4093 }
Mike Stump1eb44332009-09-09 15:08:12 +00004094 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004095 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4096 E = lhsQID->qual_end(); I != E; ++I) {
4097 ObjCProtocolDecl *lhsProto = *I;
4098 bool match = false;
4099
4100 // when comparing an id<P> on lhs with a static type on rhs,
4101 // see if static class implements all of id's protocols, directly or
4102 // through its super class and categories.
4103 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4104 E = rhsOPT->qual_end(); J != E; ++J) {
4105 ObjCProtocolDecl *rhsProto = *J;
4106 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4107 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4108 match = true;
4109 break;
4110 }
4111 }
Mike Stump1eb44332009-09-09 15:08:12 +00004112 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004113 // make sure we check the class hierarchy.
4114 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4115 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4116 E = lhsQID->qual_end(); I != E; ++I) {
4117 // when comparing an id<P> on lhs with a static type on rhs,
4118 // see if static class implements all of id's protocols, directly or
4119 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004120 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004121 match = true;
4122 break;
4123 }
4124 }
4125 }
4126 if (!match)
4127 return false;
4128 }
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Steve Naroff4084c302009-07-23 01:01:38 +00004130 return true;
4131 }
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Steve Naroff4084c302009-07-23 01:01:38 +00004133 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4134 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4135
Mike Stump1eb44332009-09-09 15:08:12 +00004136 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004137 lhs->getAsObjCInterfacePointerType()) {
4138 if (lhsOPT->qual_empty()) {
4139 bool match = false;
4140 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4141 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4142 E = rhsQID->qual_end(); I != E; ++I) {
4143 // when comparing an id<P> on lhs with a static type on rhs,
4144 // see if static class implements all of id's protocols, directly or
4145 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004146 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004147 match = true;
4148 break;
4149 }
4150 }
4151 if (!match)
4152 return false;
4153 }
4154 return true;
4155 }
Mike Stump1eb44332009-09-09 15:08:12 +00004156 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004157 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4158 E = lhsOPT->qual_end(); I != E; ++I) {
4159 ObjCProtocolDecl *lhsProto = *I;
4160 bool match = false;
4161
4162 // when comparing an id<P> on lhs with a static type on rhs,
4163 // see if static class implements all of id's protocols, directly or
4164 // through its super class and categories.
4165 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4166 E = rhsQID->qual_end(); J != E; ++J) {
4167 ObjCProtocolDecl *rhsProto = *J;
4168 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4169 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4170 match = true;
4171 break;
4172 }
4173 }
4174 if (!match)
4175 return false;
4176 }
4177 return true;
4178 }
4179 return false;
4180}
4181
Eli Friedman3d815e72008-08-22 00:56:42 +00004182/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004183/// compatible for assignment from RHS to LHS. This handles validation of any
4184/// protocol qualifiers on the LHS or RHS.
4185///
Steve Naroff14108da2009-07-10 23:34:53 +00004186bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4187 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004188 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4189 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4190
Steve Naroffde2e22d2009-07-15 18:40:39 +00004191 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004192 if (LHS->isObjCUnqualifiedIdOrClass() ||
4193 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004194 return true;
4195
John McCallc12c5bb2010-05-15 11:32:37 +00004196 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004197 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4198 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004199 false);
4200
John McCallc12c5bb2010-05-15 11:32:37 +00004201 // If we have 2 user-defined types, fall into that path.
4202 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004203 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Steve Naroff4084c302009-07-23 01:01:38 +00004205 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004206}
4207
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004208/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4209/// for providing type-safty for objective-c pointers used to pass/return
4210/// arguments in block literals. When passed as arguments, passing 'A*' where
4211/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4212/// not OK. For the return type, the opposite is not OK.
4213bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4214 const ObjCObjectPointerType *LHSOPT,
4215 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004216 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004217 return true;
4218
4219 if (LHSOPT->isObjCBuiltinType()) {
4220 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4221 }
4222
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004223 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004224 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4225 QualType(RHSOPT,0),
4226 false);
4227
4228 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4229 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4230 if (LHS && RHS) { // We have 2 user-defined types.
4231 if (LHS != RHS) {
4232 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4233 return false;
4234 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4235 return true;
4236 }
4237 else
4238 return true;
4239 }
4240 return false;
4241}
4242
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004243/// getIntersectionOfProtocols - This routine finds the intersection of set
4244/// of protocols inherited from two distinct objective-c pointer objects.
4245/// It is used to build composite qualifier list of the composite type of
4246/// the conditional expression involving two objective-c pointer objects.
4247static
4248void getIntersectionOfProtocols(ASTContext &Context,
4249 const ObjCObjectPointerType *LHSOPT,
4250 const ObjCObjectPointerType *RHSOPT,
4251 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4252
John McCallc12c5bb2010-05-15 11:32:37 +00004253 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4254 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4255 assert(LHS->getInterface() && "LHS must have an interface base");
4256 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004257
4258 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4259 unsigned LHSNumProtocols = LHS->getNumProtocols();
4260 if (LHSNumProtocols > 0)
4261 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4262 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004263 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004264 Context.CollectInheritedProtocols(LHS->getInterface(),
4265 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004266 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4267 LHSInheritedProtocols.end());
4268 }
4269
4270 unsigned RHSNumProtocols = RHS->getNumProtocols();
4271 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004272 ObjCProtocolDecl **RHSProtocols =
4273 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004274 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4275 if (InheritedProtocolSet.count(RHSProtocols[i]))
4276 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4277 }
4278 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004279 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004280 Context.CollectInheritedProtocols(RHS->getInterface(),
4281 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004282 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4283 RHSInheritedProtocols.begin(),
4284 E = RHSInheritedProtocols.end(); I != E; ++I)
4285 if (InheritedProtocolSet.count((*I)))
4286 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004287 }
4288}
4289
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004290/// areCommonBaseCompatible - Returns common base class of the two classes if
4291/// one found. Note that this is O'2 algorithm. But it will be called as the
4292/// last type comparison in a ?-exp of ObjC pointer types before a
4293/// warning is issued. So, its invokation is extremely rare.
4294QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004295 const ObjCObjectPointerType *Lptr,
4296 const ObjCObjectPointerType *Rptr) {
4297 const ObjCObjectType *LHS = Lptr->getObjectType();
4298 const ObjCObjectType *RHS = Rptr->getObjectType();
4299 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4300 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4301 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004302 return QualType();
4303
John McCallc12c5bb2010-05-15 11:32:37 +00004304 while ((LDecl = LDecl->getSuperClass())) {
4305 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004306 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004307 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4308 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4309
4310 QualType Result = QualType(LHS, 0);
4311 if (!Protocols.empty())
4312 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4313 Result = getObjCObjectPointerType(Result);
4314 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004315 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004316 }
4317
4318 return QualType();
4319}
4320
John McCallc12c5bb2010-05-15 11:32:37 +00004321bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4322 const ObjCObjectType *RHS) {
4323 assert(LHS->getInterface() && "LHS is not an interface type");
4324 assert(RHS->getInterface() && "RHS is not an interface type");
4325
Chris Lattner6ac46a42008-04-07 06:51:04 +00004326 // Verify that the base decls are compatible: the RHS must be a subclass of
4327 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004328 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004329 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Chris Lattner6ac46a42008-04-07 06:51:04 +00004331 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4332 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004333 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004334 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Chris Lattner6ac46a42008-04-07 06:51:04 +00004336 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4337 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004338 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004339 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004340
John McCallc12c5bb2010-05-15 11:32:37 +00004341 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4342 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004343 LHSPI != LHSPE; LHSPI++) {
4344 bool RHSImplementsProtocol = false;
4345
4346 // If the RHS doesn't implement the protocol on the left, the types
4347 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004348 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4349 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004350 RHSPI != RHSPE; RHSPI++) {
4351 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004352 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004353 break;
4354 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004355 }
4356 // FIXME: For better diagnostics, consider passing back the protocol name.
4357 if (!RHSImplementsProtocol)
4358 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004359 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004360 // The RHS implements all protocols listed on the LHS.
4361 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004362}
4363
Steve Naroff389bf462009-02-12 17:52:19 +00004364bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4365 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004366 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4367 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Steve Naroff14108da2009-07-10 23:34:53 +00004369 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004370 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004371
4372 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4373 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004374}
4375
Mike Stump1eb44332009-09-09 15:08:12 +00004376/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004377/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004378/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004379/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004380bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004381 if (getLangOptions().CPlusPlus)
4382 return hasSameType(LHS, RHS);
4383
Eli Friedman3d815e72008-08-22 00:56:42 +00004384 return !mergeTypes(LHS, RHS).isNull();
4385}
4386
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004387bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4388 return !mergeTypes(LHS, RHS, true).isNull();
4389}
4390
4391QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4392 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004393 const FunctionType *lbase = lhs->getAs<FunctionType>();
4394 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004395 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4396 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004397 bool allLTypes = true;
4398 bool allRTypes = true;
4399
4400 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004401 QualType retType;
4402 if (OfBlockPointer)
4403 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4404 else
4405 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004406 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004407 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004408 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004409 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004410 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004411 // FIXME: double check this
4412 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4413 // rbase->getRegParmAttr() != 0 &&
4414 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004415 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4416 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004417 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4418 lbaseInfo.getRegParm();
4419 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4420 if (NoReturn != lbaseInfo.getNoReturn() ||
4421 RegParm != lbaseInfo.getRegParm())
4422 allLTypes = false;
4423 if (NoReturn != rbaseInfo.getNoReturn() ||
4424 RegParm != rbaseInfo.getRegParm())
4425 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004426 CallingConv lcc = lbaseInfo.getCC();
4427 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004428 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004429 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004430 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004431
Eli Friedman3d815e72008-08-22 00:56:42 +00004432 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004433 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4434 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004435 unsigned lproto_nargs = lproto->getNumArgs();
4436 unsigned rproto_nargs = rproto->getNumArgs();
4437
4438 // Compatible functions must have the same number of arguments
4439 if (lproto_nargs != rproto_nargs)
4440 return QualType();
4441
4442 // Variadic and non-variadic functions aren't compatible
4443 if (lproto->isVariadic() != rproto->isVariadic())
4444 return QualType();
4445
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004446 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4447 return QualType();
4448
Eli Friedman3d815e72008-08-22 00:56:42 +00004449 // Check argument compatibility
4450 llvm::SmallVector<QualType, 10> types;
4451 for (unsigned i = 0; i < lproto_nargs; i++) {
4452 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4453 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004454 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004455 if (argtype.isNull()) return QualType();
4456 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004457 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4458 allLTypes = false;
4459 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4460 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004461 }
4462 if (allLTypes) return lhs;
4463 if (allRTypes) return rhs;
4464 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004465 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004466 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004467 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004468 }
4469
4470 if (lproto) allRTypes = false;
4471 if (rproto) allLTypes = false;
4472
Douglas Gregor72564e72009-02-26 23:50:07 +00004473 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004474 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004475 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004476 if (proto->isVariadic()) return QualType();
4477 // Check that the types are compatible with the types that
4478 // would result from default argument promotions (C99 6.7.5.3p15).
4479 // The only types actually affected are promotable integer
4480 // types and floats, which would be passed as a different
4481 // type depending on whether the prototype is visible.
4482 unsigned proto_nargs = proto->getNumArgs();
4483 for (unsigned i = 0; i < proto_nargs; ++i) {
4484 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004485
4486 // Look at the promotion type of enum types, since that is the type used
4487 // to pass enum values.
4488 if (const EnumType *Enum = argTy->getAs<EnumType>())
4489 argTy = Enum->getDecl()->getPromotionType();
4490
Eli Friedman3d815e72008-08-22 00:56:42 +00004491 if (argTy->isPromotableIntegerType() ||
4492 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4493 return QualType();
4494 }
4495
4496 if (allLTypes) return lhs;
4497 if (allRTypes) return rhs;
4498 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004499 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004500 proto->getTypeQuals(),
4501 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004502 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004503 }
4504
4505 if (allLTypes) return lhs;
4506 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004507 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004508 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004509}
4510
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004511QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4512 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004513 // C++ [expr]: If an expression initially has the type "reference to T", the
4514 // type is adjusted to "T" prior to any further analysis, the expression
4515 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004516 // expression is an lvalue unless the reference is an rvalue reference and
4517 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004518 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4519 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4520
Eli Friedman3d815e72008-08-22 00:56:42 +00004521 QualType LHSCan = getCanonicalType(LHS),
4522 RHSCan = getCanonicalType(RHS);
4523
4524 // If two types are identical, they are compatible.
4525 if (LHSCan == RHSCan)
4526 return LHS;
4527
John McCall0953e762009-09-24 19:53:00 +00004528 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004529 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4530 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004531 if (LQuals != RQuals) {
4532 // If any of these qualifiers are different, we have a type
4533 // mismatch.
4534 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4535 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4536 return QualType();
4537
4538 // Exactly one GC qualifier difference is allowed: __strong is
4539 // okay if the other type has no GC qualifier but is an Objective
4540 // C object pointer (i.e. implicitly strong by default). We fix
4541 // this by pretending that the unqualified type was actually
4542 // qualified __strong.
4543 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4544 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4545 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4546
4547 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4548 return QualType();
4549
4550 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4551 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4552 }
4553 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4554 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4555 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004556 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004557 }
4558
4559 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004560
Eli Friedman852d63b2009-06-01 01:22:52 +00004561 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4562 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004563
Chris Lattner1adb8832008-01-14 05:45:46 +00004564 // We want to consider the two function types to be the same for these
4565 // comparisons, just force one to the other.
4566 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4567 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004568
4569 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004570 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4571 LHSClass = Type::ConstantArray;
4572 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4573 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004574
John McCallc12c5bb2010-05-15 11:32:37 +00004575 // ObjCInterfaces are just specialized ObjCObjects.
4576 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4577 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4578
Nate Begeman213541a2008-04-18 23:10:10 +00004579 // Canonicalize ExtVector -> Vector.
4580 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4581 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004582
Chris Lattnera36a61f2008-04-07 05:43:21 +00004583 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004584 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004585 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004586 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004587 // Compatibility is based on the underlying type, not the promotion
4588 // type.
John McCall183700f2009-09-21 23:43:11 +00004589 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004590 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4591 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004592 }
John McCall183700f2009-09-21 23:43:11 +00004593 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004594 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4595 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004596 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004597
Eli Friedman3d815e72008-08-22 00:56:42 +00004598 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004599 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004600
Steve Naroff4a746782008-01-09 22:43:08 +00004601 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004602 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004603#define TYPE(Class, Base)
4604#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004605#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004606#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4607#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4608#include "clang/AST/TypeNodes.def"
4609 assert(false && "Non-canonical and dependent types shouldn't get here");
4610 return QualType();
4611
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004612 case Type::LValueReference:
4613 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004614 case Type::MemberPointer:
4615 assert(false && "C++ should never be in mergeTypes");
4616 return QualType();
4617
John McCallc12c5bb2010-05-15 11:32:37 +00004618 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004619 case Type::IncompleteArray:
4620 case Type::VariableArray:
4621 case Type::FunctionProto:
4622 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004623 assert(false && "Types are eliminated above");
4624 return QualType();
4625
Chris Lattner1adb8832008-01-14 05:45:46 +00004626 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004627 {
4628 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004629 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4630 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004631 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4632 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004633 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004634 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004635 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004636 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004637 return getPointerType(ResultType);
4638 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004639 case Type::BlockPointer:
4640 {
4641 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004642 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4643 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004644 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004645 if (ResultType.isNull()) return QualType();
4646 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4647 return LHS;
4648 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4649 return RHS;
4650 return getBlockPointerType(ResultType);
4651 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004652 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004653 {
4654 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4655 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4656 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4657 return QualType();
4658
4659 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4660 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4661 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4662 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004663 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4664 return LHS;
4665 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4666 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004667 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4668 ArrayType::ArraySizeModifier(), 0);
4669 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4670 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004671 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4672 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004673 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4674 return LHS;
4675 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4676 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004677 if (LVAT) {
4678 // FIXME: This isn't correct! But tricky to implement because
4679 // the array's size has to be the size of LHS, but the type
4680 // has to be different.
4681 return LHS;
4682 }
4683 if (RVAT) {
4684 // FIXME: This isn't correct! But tricky to implement because
4685 // the array's size has to be the size of RHS, but the type
4686 // has to be different.
4687 return RHS;
4688 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004689 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4690 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004691 return getIncompleteArrayType(ResultType,
4692 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004693 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004694 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004695 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004696 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004697 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004698 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004699 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004700 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004701 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004702 case Type::Complex:
4703 // Distinct complex types are incompatible.
4704 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004705 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004706 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004707 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4708 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004709 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004710 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004711 case Type::ObjCObject: {
4712 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004713 // FIXME: This should be type compatibility, e.g. whether
4714 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004715 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4716 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4717 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004718 return LHS;
4719
Eli Friedman3d815e72008-08-22 00:56:42 +00004720 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004721 }
Steve Naroff14108da2009-07-10 23:34:53 +00004722 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004723 if (OfBlockPointer) {
4724 if (canAssignObjCInterfacesInBlockPointer(
4725 LHS->getAs<ObjCObjectPointerType>(),
4726 RHS->getAs<ObjCObjectPointerType>()))
4727 return LHS;
4728 return QualType();
4729 }
John McCall183700f2009-09-21 23:43:11 +00004730 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4731 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004732 return LHS;
4733
Steve Naroffbc76dd02008-12-10 22:14:21 +00004734 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004735 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004736 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004737
4738 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004739}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004740
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004741/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4742/// 'RHS' attributes and returns the merged version; including for function
4743/// return types.
4744QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4745 QualType LHSCan = getCanonicalType(LHS),
4746 RHSCan = getCanonicalType(RHS);
4747 // If two types are identical, they are compatible.
4748 if (LHSCan == RHSCan)
4749 return LHS;
4750 if (RHSCan->isFunctionType()) {
4751 if (!LHSCan->isFunctionType())
4752 return QualType();
4753 QualType OldReturnType =
4754 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4755 QualType NewReturnType =
4756 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4757 QualType ResReturnType =
4758 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4759 if (ResReturnType.isNull())
4760 return QualType();
4761 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4762 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4763 // In either case, use OldReturnType to build the new function type.
4764 const FunctionType *F = LHS->getAs<FunctionType>();
4765 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4766 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4767 QualType ResultType
4768 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4769 FPT->getNumArgs(), FPT->isVariadic(),
4770 FPT->getTypeQuals(),
4771 FPT->hasExceptionSpec(),
4772 FPT->hasAnyExceptionSpec(),
4773 FPT->getNumExceptions(),
4774 FPT->exception_begin(),
4775 Info);
4776 return ResultType;
4777 }
4778 }
4779 return QualType();
4780 }
4781
4782 // If the qualifiers are different, the types can still be merged.
4783 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4784 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4785 if (LQuals != RQuals) {
4786 // If any of these qualifiers are different, we have a type mismatch.
4787 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4788 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4789 return QualType();
4790
4791 // Exactly one GC qualifier difference is allowed: __strong is
4792 // okay if the other type has no GC qualifier but is an Objective
4793 // C object pointer (i.e. implicitly strong by default). We fix
4794 // this by pretending that the unqualified type was actually
4795 // qualified __strong.
4796 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4797 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4798 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4799
4800 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4801 return QualType();
4802
4803 if (GC_L == Qualifiers::Strong)
4804 return LHS;
4805 if (GC_R == Qualifiers::Strong)
4806 return RHS;
4807 return QualType();
4808 }
4809
4810 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4811 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4812 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4813 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4814 if (ResQT == LHSBaseQT)
4815 return LHS;
4816 if (ResQT == RHSBaseQT)
4817 return RHS;
4818 }
4819 return QualType();
4820}
4821
Chris Lattner5426bf62008-04-07 07:01:58 +00004822//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004823// Integer Predicates
4824//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004825
Eli Friedmanad74a752008-06-28 06:23:08 +00004826unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004827 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004828 return 1;
John McCall842aef82009-12-09 09:09:27 +00004829 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004830 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004831 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004832 return (unsigned)getTypeSize(T);
4833}
4834
4835QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4836 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004837
4838 // Turn <4 x signed int> -> <4 x unsigned int>
4839 if (const VectorType *VTy = T->getAs<VectorType>())
4840 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004841 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004842
4843 // For enums, we return the unsigned version of the base type.
4844 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004845 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004846
4847 const BuiltinType *BTy = T->getAs<BuiltinType>();
4848 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004849 switch (BTy->getKind()) {
4850 case BuiltinType::Char_S:
4851 case BuiltinType::SChar:
4852 return UnsignedCharTy;
4853 case BuiltinType::Short:
4854 return UnsignedShortTy;
4855 case BuiltinType::Int:
4856 return UnsignedIntTy;
4857 case BuiltinType::Long:
4858 return UnsignedLongTy;
4859 case BuiltinType::LongLong:
4860 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004861 case BuiltinType::Int128:
4862 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004863 default:
4864 assert(0 && "Unexpected signed integer type");
4865 return QualType();
4866 }
4867}
4868
Douglas Gregor2cf26342009-04-09 22:27:44 +00004869ExternalASTSource::~ExternalASTSource() { }
4870
4871void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004872
4873
4874//===----------------------------------------------------------------------===//
4875// Builtin Type Computation
4876//===----------------------------------------------------------------------===//
4877
4878/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4879/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004880static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004881 ASTContext::GetBuiltinTypeError &Error,
4882 bool AllowTypeModifiers = true) {
4883 // Modifiers.
4884 int HowLong = 0;
4885 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004886
Chris Lattner86df27b2009-06-14 00:45:47 +00004887 // Read the modifiers first.
4888 bool Done = false;
4889 while (!Done) {
4890 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004891 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004892 case 'S':
4893 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4894 assert(!Signed && "Can't use 'S' modifier multiple times!");
4895 Signed = true;
4896 break;
4897 case 'U':
4898 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4899 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4900 Unsigned = true;
4901 break;
4902 case 'L':
4903 assert(HowLong <= 2 && "Can't have LLLL modifier");
4904 ++HowLong;
4905 break;
4906 }
4907 }
4908
4909 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004910
Chris Lattner86df27b2009-06-14 00:45:47 +00004911 // Read the base type.
4912 switch (*Str++) {
4913 default: assert(0 && "Unknown builtin type letter!");
4914 case 'v':
4915 assert(HowLong == 0 && !Signed && !Unsigned &&
4916 "Bad modifiers used with 'v'!");
4917 Type = Context.VoidTy;
4918 break;
4919 case 'f':
4920 assert(HowLong == 0 && !Signed && !Unsigned &&
4921 "Bad modifiers used with 'f'!");
4922 Type = Context.FloatTy;
4923 break;
4924 case 'd':
4925 assert(HowLong < 2 && !Signed && !Unsigned &&
4926 "Bad modifiers used with 'd'!");
4927 if (HowLong)
4928 Type = Context.LongDoubleTy;
4929 else
4930 Type = Context.DoubleTy;
4931 break;
4932 case 's':
4933 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4934 if (Unsigned)
4935 Type = Context.UnsignedShortTy;
4936 else
4937 Type = Context.ShortTy;
4938 break;
4939 case 'i':
4940 if (HowLong == 3)
4941 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4942 else if (HowLong == 2)
4943 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4944 else if (HowLong == 1)
4945 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4946 else
4947 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4948 break;
4949 case 'c':
4950 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4951 if (Signed)
4952 Type = Context.SignedCharTy;
4953 else if (Unsigned)
4954 Type = Context.UnsignedCharTy;
4955 else
4956 Type = Context.CharTy;
4957 break;
4958 case 'b': // boolean
4959 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4960 Type = Context.BoolTy;
4961 break;
4962 case 'z': // size_t.
4963 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4964 Type = Context.getSizeType();
4965 break;
4966 case 'F':
4967 Type = Context.getCFConstantStringType();
4968 break;
4969 case 'a':
4970 Type = Context.getBuiltinVaListType();
4971 assert(!Type.isNull() && "builtin va list type not initialized!");
4972 break;
4973 case 'A':
4974 // This is a "reference" to a va_list; however, what exactly
4975 // this means depends on how va_list is defined. There are two
4976 // different kinds of va_list: ones passed by value, and ones
4977 // passed by reference. An example of a by-value va_list is
4978 // x86, where va_list is a char*. An example of by-ref va_list
4979 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4980 // we want this argument to be a char*&; for x86-64, we want
4981 // it to be a __va_list_tag*.
4982 Type = Context.getBuiltinVaListType();
4983 assert(!Type.isNull() && "builtin va list type not initialized!");
4984 if (Type->isArrayType()) {
4985 Type = Context.getArrayDecayedType(Type);
4986 } else {
4987 Type = Context.getLValueReferenceType(Type);
4988 }
4989 break;
4990 case 'V': {
4991 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004992 unsigned NumElements = strtoul(Str, &End, 10);
4993 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004994
Chris Lattner86df27b2009-06-14 00:45:47 +00004995 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004996
Chris Lattner86df27b2009-06-14 00:45:47 +00004997 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004998 // FIXME: Don't know what to do about AltiVec.
4999 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00005000 break;
5001 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005002 case 'X': {
5003 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5004 Type = Context.getComplexType(ElementType);
5005 break;
5006 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005007 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005008 Type = Context.getFILEType();
5009 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005010 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005011 return QualType();
5012 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005013 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005014 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005015 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005016 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005017 else
5018 Type = Context.getjmp_bufType();
5019
Mike Stumpfd612db2009-07-28 23:47:15 +00005020 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005021 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005022 return QualType();
5023 }
5024 break;
Mike Stump782fa302009-07-28 02:25:19 +00005025 }
Mike Stump1eb44332009-09-09 15:08:12 +00005026
Chris Lattner86df27b2009-06-14 00:45:47 +00005027 if (!AllowTypeModifiers)
5028 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005029
Chris Lattner86df27b2009-06-14 00:45:47 +00005030 Done = false;
5031 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005032 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005033 default: Done = true; --Str; break;
5034 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005035 case '&':
John McCall187ab372010-03-12 04:21:28 +00005036 {
5037 // Both pointers and references can have their pointee types
5038 // qualified with an address space.
5039 char *End;
5040 unsigned AddrSpace = strtoul(Str, &End, 10);
5041 if (End != Str && AddrSpace != 0) {
5042 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5043 Str = End;
5044 }
5045 }
5046 if (c == '*')
5047 Type = Context.getPointerType(Type);
5048 else
5049 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005050 break;
5051 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5052 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005053 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005054 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005055 case 'D':
5056 Type = Context.getVolatileType(Type);
5057 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005058 }
5059 }
Mike Stump1eb44332009-09-09 15:08:12 +00005060
Chris Lattner86df27b2009-06-14 00:45:47 +00005061 return Type;
5062}
5063
5064/// GetBuiltinType - Return the type for the specified builtin.
5065QualType ASTContext::GetBuiltinType(unsigned id,
5066 GetBuiltinTypeError &Error) {
5067 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005068
Chris Lattner86df27b2009-06-14 00:45:47 +00005069 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005070
Chris Lattner86df27b2009-06-14 00:45:47 +00005071 Error = GE_None;
5072 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5073 if (Error != GE_None)
5074 return QualType();
5075 while (TypeStr[0] && TypeStr[0] != '.') {
5076 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5077 if (Error != GE_None)
5078 return QualType();
5079
5080 // Do array -> pointer decay. The builtin should use the decayed type.
5081 if (Ty->isArrayType())
5082 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005083
Chris Lattner86df27b2009-06-14 00:45:47 +00005084 ArgTypes.push_back(Ty);
5085 }
5086
5087 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5088 "'.' should only occur at end of builtin type list!");
5089
5090 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5091 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5092 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005093
5094 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005095 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005096 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005097 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005098}
Eli Friedmana95d7572009-08-19 07:44:53 +00005099
5100QualType
5101ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5102 // Perform the usual unary conversions. We do this early so that
5103 // integral promotions to "int" can allow us to exit early, in the
5104 // lhs == rhs check. Also, for conversion purposes, we ignore any
5105 // qualifiers. For example, "const float" and "float" are
5106 // equivalent.
5107 if (lhs->isPromotableIntegerType())
5108 lhs = getPromotedIntegerType(lhs);
5109 else
5110 lhs = lhs.getUnqualifiedType();
5111 if (rhs->isPromotableIntegerType())
5112 rhs = getPromotedIntegerType(rhs);
5113 else
5114 rhs = rhs.getUnqualifiedType();
5115
5116 // If both types are identical, no conversion is needed.
5117 if (lhs == rhs)
5118 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005119
Eli Friedmana95d7572009-08-19 07:44:53 +00005120 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5121 // The caller can deal with this (e.g. pointer + int).
5122 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5123 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005124
5125 // At this point, we have two different arithmetic types.
5126
Eli Friedmana95d7572009-08-19 07:44:53 +00005127 // Handle complex types first (C99 6.3.1.8p1).
5128 if (lhs->isComplexType() || rhs->isComplexType()) {
5129 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005130 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005131 // convert the rhs to the lhs complex type.
5132 return lhs;
5133 }
Mike Stump1eb44332009-09-09 15:08:12 +00005134 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005135 // convert the lhs to the rhs complex type.
5136 return rhs;
5137 }
5138 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005139 // When both operands are complex, the shorter operand is converted to the
5140 // type of the longer, and that is the type of the result. This corresponds
5141 // to what is done when combining two real floating-point operands.
5142 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005143 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005144 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005145 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005146 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005147 // "double _Complex" is promoted to "long double _Complex".
5148 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005149
5150 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005151 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005152 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005153 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005154 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005155 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5156 // domains match. This is a requirement for our implementation, C99
5157 // does not require this promotion.
5158 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5159 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5160 return rhs;
5161 } else { // handle "_Complex double, double".
5162 return lhs;
5163 }
5164 }
5165 return lhs; // The domain/size match exactly.
5166 }
5167 // Now handle "real" floating types (i.e. float, double, long double).
5168 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5169 // if we have an integer operand, the result is the real floating type.
5170 if (rhs->isIntegerType()) {
5171 // convert rhs to the lhs floating point type.
5172 return lhs;
5173 }
5174 if (rhs->isComplexIntegerType()) {
5175 // convert rhs to the complex floating point type.
5176 return getComplexType(lhs);
5177 }
5178 if (lhs->isIntegerType()) {
5179 // convert lhs to the rhs floating point type.
5180 return rhs;
5181 }
Mike Stump1eb44332009-09-09 15:08:12 +00005182 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005183 // convert lhs to the complex floating point type.
5184 return getComplexType(rhs);
5185 }
5186 // We have two real floating types, float/complex combos were handled above.
5187 // Convert the smaller operand to the bigger result.
5188 int result = getFloatingTypeOrder(lhs, rhs);
5189 if (result > 0) // convert the rhs
5190 return lhs;
5191 assert(result < 0 && "illegal float comparison");
5192 return rhs; // convert the lhs
5193 }
5194 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5195 // Handle GCC complex int extension.
5196 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5197 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5198
5199 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005200 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005201 rhsComplexInt->getElementType()) >= 0)
5202 return lhs; // convert the rhs
5203 return rhs;
5204 } else if (lhsComplexInt && rhs->isIntegerType()) {
5205 // convert the rhs to the lhs complex type.
5206 return lhs;
5207 } else if (rhsComplexInt && lhs->isIntegerType()) {
5208 // convert the lhs to the rhs complex type.
5209 return rhs;
5210 }
5211 }
5212 // Finally, we have two differing integer types.
5213 // The rules for this case are in C99 6.3.1.8
5214 int compare = getIntegerTypeOrder(lhs, rhs);
5215 bool lhsSigned = lhs->isSignedIntegerType(),
5216 rhsSigned = rhs->isSignedIntegerType();
5217 QualType destType;
5218 if (lhsSigned == rhsSigned) {
5219 // Same signedness; use the higher-ranked type
5220 destType = compare >= 0 ? lhs : rhs;
5221 } else if (compare != (lhsSigned ? 1 : -1)) {
5222 // The unsigned type has greater than or equal rank to the
5223 // signed type, so use the unsigned type
5224 destType = lhsSigned ? rhs : lhs;
5225 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5226 // The two types are different widths; if we are here, that
5227 // means the signed type is larger than the unsigned type, so
5228 // use the signed type.
5229 destType = lhsSigned ? lhs : rhs;
5230 } else {
5231 // The signed type is higher-ranked than the unsigned type,
5232 // but isn't actually any bigger (like unsigned int and long
5233 // on most 32-bit systems). Use the unsigned type corresponding
5234 // to the signed type.
5235 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5236 }
5237 return destType;
5238}